I’m trying to make a chart that displays cryptocurrency prices using the CoinGeckoAPI and Chart.js. The data will be updated about every minute or so. I want my chart x-axis to look similar to this:
My x-axis data is an array of unix time values that I need to convert to Date before setting them as labels in the chart. I’m using SignalR and a background task in an ASP.NET Core MVC application to periodically send CoinGeckoAPI data to the client.
How can I set specific dynamic values as the x-axis ticks? Ideally the ticks would be set to something like every third hour within my dataset.
HTML:
<canvas id="myChart" width="400" height="400"></canvas>
JavaScript:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript">
//Establish SignalR connection
var connection = new signalR.HubConnectionBuilder().withUrl("/hub").build();
//Set up chart and initial empty configuration
const config = {
type: 'line',
data: {},
options: {}
};
const myChart = new Chart(document.getElementById('myChart'),
config);
//Pass data from SignalR Hub to client
connection.on("CryptoPriceUpdated", function (unixTimeArray, priceArray) {
//Convert unix time array to Date array with desired date formatting
var formattedDateArray = new Array();
for (var i = 0; i < unixTimeArray.length - 1; i++) {
var dateTemp = new Date(unixTimeArray[i]);
formattedDateArray[i] = dateTemp.getHours() + ':' + dateTemp.getMinutes();
}
//Configure chart with new data
var labels = formattedDateArray;
var data = {
labels: labels,
datasets: [{
label: 'Price',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
radius: 1,
data: priceArray
}]
};
var options = {
responsive: true,
}
//Update chart
myChart.data = data;
myChart.options = options;
myChart.update();
});
connection.start();
</script>