I have been working with the Chart.js in order to render a json data into cartesian time chart. The data is converted from List<tuple<string, int>> from a service class into json data where the data is made up of Date and time as string type and count as an int. This part of the code is done in view (cshtml).
From the json data, it was passed to the script part of the cshtml in order to render the charts, the first chart is rendered for the Pie chart using different data type (Not part of the question) but when it comes to the line chart for rendering the cartesian it causes an error saying "Uncaught Error: This method is not implemented: Check that a complete date adapter is provided" and it is called/appear when it tries to render the new Chart(ctx...) part of the code in the line chart function. What am I doing wrong here and how can I solve it?
@{
var ID = Model.FirstOrDefault()?.ID; // Get the ID of the first item in the list;
var DetailCounts = await Service.GetDetailChartDataAsync(ID.Value);
var DetailCounts2 = await Service.GetDetailChartDataAsync(ID.Value);
var jsonDetailData = Newtonsoft.Json.JsonConvert.SerializeObject(DetailCounts);
var jsonDetailData2 = Newtonsoft.Json.JsonConvert.SerializeObject(DetailCounts2);
}
<!DOCTYPE html>
<html>
<head>
<title>Chart Example</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="col">
<div class="row custom-row-height my-auto">
<div class="col" id="DetailChartdiv">
<div style="width: 400px; height: 400px;" class="container-fluid">
<header class="fw-bold"> Current Information</header>
<canvas id="DetailChart">
</canvas>
</div>
</div>
</div>
<div class="col">
<div class="row custom-row-height my-auto">
<div class="col" id="DetailChart2div">
<div style="width: 400px; height: 400px;" class="container-fluid">
<header class="fw-bold">Current Information</header>
<canvas id="DetailChart2"></canvas>
</div>
</div>
</div>
</div>
<script>
// Retrieve the JSON data from the hidden field
var jsonDicData = @Html.Raw(jsonDetailData);
var jsonDicData2 = @Html.Raw(jsonDetailData2);
// Parse the data and prepare it for the line chart
const parsedData2 = jsonDicData2.map(entry => ({
t: new Date(entry.Item1),
y: entry.Item2
}));
// Function to render the pie chart using Chart.js
function renderPieChart(data, canvasid) {
var canvas = document.getElementById(canvasid);
var ctx = canvas.getContext('2d');
new Chart(ctx, {
type: 'pie',
data: {
labels: Object.keys(data),
datasets: [{
data: Object.values(data),
borderWidth: 1
}]
},
options: {
// Additional options and configurations for the pie chart can be added here
plugins: {
colorschemes: {
scheme: 'brewer.Paired12' // Example color scheme
}
}
}
});
}
// Function to render the line chart using Chart.js
function renderLineChart(data, canvasid) {
var canvas = document.getElementById(canvasid);
var ctx = canvas.getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Count',
data: data,
borderColor: 'rgb(75, 192, 192)'
}]
},
options: {
scales: {
x: {
type: 'time',
time: {
unit: 'day' // Adjust according to your data
}
},
y: {
beginAtZero: true
}
}
}
});
}
// Call the rendering functions with the retrieved JSON data
renderPieChart(jsonDicData, 'DetailChart');
renderLineChart(parsedData2, 'DetailChart2');
</script>
</body>
</html>
my output json data that are being used in the chart is the following:
{Item1: '03/08/2023 07:46:11', Item2: 0}
and the parsed is the following:
{t: Wed Mar 08 2023 07:46:11 GMT+0000 (Greenwich Mean Time), y: 0}
I am also using the latest version of the Chart.js package.
Edit 1:
I have added the following packages:
<meta charset="utf-8" />
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script> -->
<!-- <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script> -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
However, I am getting the same outcome (Error).
Edit 2:
If I used the following code:
function renderLineChart(parsedData, canvasid) {
var canvas = document.getElementById(canvasid);
var ctx = canvas.getContext('2d');
if (!window.chartInstances) {
window.chartInstances = {}; // Create a global object to store chart instances
}
if (!window.chartInstances[canvasid]) {
// Create a new Chart.js instance if it doesn't exist
window.chartInstances[canvasid] = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Count',
data: parsedData,
borderColor: 'rgb(75, 192, 192)',
fill: false
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
},
scaleLabel: {
display: true,
labelString: 'Date'
}
}],
yAxes: [{
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: 'Count'
}
}]
}
}
});
} else {
// Update the existing Chart.js instance with new data and options
window.chartInstances[canvasid].data.labels = Object.keys(parsedData);
window.chartInstances[canvasid].data.datasets[0].data = Object.values(parsedData);
window.chartInstances[canvasid].update();
}
}
I got the following plot below:

I am also getting the following errors:
Invalid scale configuration for scale: xAxes
Invalid scale configuration for scale: yAxes
Edit 3:
function renderLineChart(parsedData, canvasid) {
var canvas = document.getElementById(canvasid);
var ctx = canvas.getContext('2d');
if (!window.chartInstances) {
window.chartInstances = {}; // Create a global object to store chart instances
}
if (!window.chartInstances[canvasid]) {
// Create a new Chart.js instance if it doesn't exist
window.chartInstances[canvasid] = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Count',
data: parsedData,
borderColor: 'rgb(75, 192, 192)',
fill: false
}]
},
options: {
scales: {
x: [{
type: 'time',
time: {
unit: 'day' // Adjust according to your data
},
title: {
display: true,
text: 'Date'
}
}],
y: [{
ticks: {
beginAtZero: true
},
title: {
display: true,
text: 'Count'
}
}]
}
}
});
} else {
// Update the existing Chart.js instance with new data and options
window.chartInstances[canvasid].data.labels = Object.keys(parsedData);
window.chartInstances[canvasid].data.datasets[0].data = Object.values(parsedData);
window.chartInstances[canvasid].update();
}
}
still same error and output
Edit 4:
I managed to get the plot to present the data, however, how can I get the x-axis label to render the date and time?
// Function to render the line chart using Chart.js
function renderLineChart(data, canvasid) {
var canvas = document.getElementById(canvasid);
var ctx = canvas.getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Count',
data: data,
borderColor: 'rgb(75, 192, 192)'
}]
},
options: {
scales: {
x: {
type: 'time',
time: {
unit: 'hour' // Adjust according to your data
}
},
y: {
beginAtZero: true
}
}
}
});
}
Edit 5: Will it be possible to render custom tooltipformat? see my following line function:
// Function to render the line chart using Chart.js
function renderLineChart(data1, data2, canvasid) {
var canvas = document.getElementById(canvasid);
var ctx = canvas.getContext('2d');
console.log("Rendering line chart...");
// Destroy old line chart if it exists
if (window.chartInstances[canvasid]) {
console.log('Destroying old line chart...');
window.chartInstances[canvasid].destroy();
}
console.log("Creating new line chart...");
if (!window.chartInstances[canvasid])
{
window.chartInstances = {};
// Create a new Chart.js instance if it doesn't exist
window.chartInstances[canvasid] = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Total Count (1)',
data: data1.map(item => ({
x: item.x,
y: item.y,
string1: item.string1,
string2: item.string2
})),
borderColor: 'rgb(75, 192, 192)'
},
{
label: 'Total Count (2)',
data: data2.map(item => ({
x: item.x,
y: item.y,
string1: item.string1,
string2: item.string2
})),
borderColor: 'rgb(255, 99, 132)'
}]
},
options: {
scales: {
x: {
type: 'time', // Use time scale for x-axis
time: {
tooltipFormat: dd/MM/yyyy HH:mm:ss' // Format for tooltip display
displayFormats: {
second: 'dd/MM HH:mm:ss', // Format for x-axis labels
},
},
title: {
display: true,
text: 'Timestamp',
},
},
y: {
beginAtZero: true,
title:{
display: true,
text: 'Counts'
}
}
},
plugins: {
tooltip: {
callbacks: {
tooltipFormat: function (context) {
const xValue = context.parsed.x;
const yValue = context.parsed.y;
const dataset = context.dataset;
const dataItem = dataset.data[context.dataIndex];
const string1 = dataItem.string1 || '';
const string2 = dataItem.string2 || '';
const label2 = 'Current Data:';
return `${label2} ${xValue} - ${yValue} - ${string1} - ${string2}`;
}
}
}
}
}
});
}
else
{
// Update the existing Chart.js instance with new data and options
window.chartInstances[canvasid].data.datasets[0].data = data1;
window.chartInstances[canvasid].data.datasets[1].data = data2;
window.chartInstances[canvasid].update();
}
}
