I'm not really good in javascript, a language I always have difficulties to understand and work with. I'm working on a Django project where I need to pass a list to Chart.js to display a graph according to a specific Model.
The problem I have is trying to pass a list to javascript from Django in order to display data if they are available or not.
Let's say I have a python list from a Model attribute :
[10, 20, None, 30, 40, None, 50]
I need Chart.js to display data depending if they is a value for each axis point and nothing if they is None. When I try to pass the list with json.dump() and then in my template with {{ my_list|safe }} it display it like this :
['10', '20', 'None', '30', '40', 'None', '50']
Everything is diplayed as str when it should be either int or None/null value. How should I do if I need chart.js to have values as they are in backend ?
Hoping my problem is clear enough, if not let me know and I'll try to better explain !
Thank you in advance for your precious help.
Chart.js code
var ctx = document.getElementById('financial-chart');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: {{ tab_year|safe }}",
datasets:
[{
label: 'Sales',
data: {{ tab_sales|safe }},
backgroundColor: "#4C81B6",
borderColor: "#4C81B6",
borderWidth: 3,
tension: 0.3,
fill: false
},
{
label: 'Profit',
data: {{ tab_profit|safe }},
backgroundColor: "#DF5558",
borderColor: "#DF5558",
borderWidth: 3,
tension: 0.3,
fill: false
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
SOLVED
As mentionned by elyas the extra quotation mark was the reason causing the issue. Nones are now interpreted as null as they should be.
I am displaying a mixed bar and line chart using chartjs. I have successfully managed to display different content in the tooltip when your hover over the line chart, or the bars, but using the same condition does not work to display a different title:
callbacks: {
title: function(tooltipItem, data) {
if (tooltipItem.datasetIndex === 0){
return data['datasets'][0]['label'];
}else{
return data['datasets'][1]['label'];
}
}
}
I am using PHP values to populate data into the main chart. Here is the code for the main chart:
var ctx_<?=$chartname?> = document.getElementById('<?=$chartname?>').getContext('2d');
new Chart(ctx_<?=$chartname?>, {
type: 'bar',
data: {
labels: [<?=$labels?>], //label array needs to go here
datasets: [{
label: 'Overall Average Score',
notes: ['','','','',''],
data: [<?=$averages?>],
pointBackgroundColor: '#6600CC',
pointRadius: 6,
pointBorderColor: 'rgb(255, 255, 255)',
pointHoverRadius:8,
pointHoverBorderWidth: 2,
pointHoverBorderColor: 'rgb(255, 255, 255)',
fill: false,
// Changes this dataset to become a line
type: 'line'
},{
label: '<?=$forename?>\'s Score',
notes: [<?=$notes?>],
data: [<?=$scores?>] //data array needs to go in here
}],
},
options: groupBarChartOptions
});
However, instead of populating the tooltip title as 'Overall Average Score' it populates the line graph tooltip title of 'Pupil Name's Score'
I am using the same
if (tooltipItem.datasetIndex === 0){
condition in the following label callback, and it works.
This should work for what you want:
title: (tooltipItem, data) => {
return data['datasets'][tooltipItem[0].datasetIndex]['label']
}
working example: https://jsfiddle.net/Leelenaleee/bcwky40z/4/
I have created a Radar Chart using ChartJS as follows:
HTML:
<canvas id="radarChartTest" width="800" height="600"></canvas>
<script>
radarChartTest(["A", "B", "C", "D"], [5, 10, 15, 20], document.getElementById("radarChartTest"));
</script>
JS:
function radarChartTest(categories, totals, chartToPopulate) {
var chartDisplay = chartToPopulate;
var newChart = new Chart(chartDisplay, {
type: 'radar',
data: {
labels: categories,
datasets: [
{
data: totals,
label: "test"
}
]
}
})
}
JSFiddle
The chart draws and populates fine. However, when I hover over a radar point, it does not display the value:
There should be a number after test:.
I am expecting something similar to this:
Am I missing an attribute or something? I have checked the documentation but could not spot anything for it. I have also compared my code to where I found (a working example), but could not spot anything there either.
This is due to a bug in the that version (2.8.0) of Chart.js (Values on Tooltip of Radar Chart is not shown).
You can fix it by upgrading to 2.9.0.
Updated working Fiddle with version 2.9.0
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.0"> </script>
As far as I can tell I had the same problem a while ago, maybe, because I'll need to research a little more about this issue, the problem is due to a previous version of Chart.js. In any case here is a CodePen with a solution to your problem RadarChart Example. Hope this helps. Cheers, sigfried.
UPDATE
Since this is not only about the answers here is the link from the documentation of Chart.js that I used to solve the tooltips issue Label Callbacks.
I tried to re-create the problem you have but it looks all good to me.(A number after "total")
Since you only post part of your code, I am not sure where you are confused.
So I attached the full code I created here. Compare it to your code and let me know if you still can't generate the figure you want.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript chart</h2>
<p>Radar Chart Demo </p>
<canvas id="radar-chart" width="800" height="600"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js">
</script>
<script>
function radarChart(categories, totals, averages, chartToPopulate, chartTitle) {
var chartDisplay = chartToPopulate;
var newChart = new Chart(chartDisplay, {
type: 'radar',
data: {
labels: categories,
datasets: [
{
data: averages,
pointBackgroundColor: ["rgba(199,54,54,1)", "rgba(199,54,122,1)", "rgba(199,54,154,1)", "rgba(146,54,199,1)", "rgba(69,54,199,1)", "rgba(54,103,199,1)", "rgba(54,165,199,1)", "rgba(54,199,180,1)"],
pointBorderColor: ["rgba(199,54,54,1)", "rgba(199,54,122,1)", "rgba(199,54,154,1)", "rgba(146,54,199,1)", "rgba(69,54,199,1)", "rgba(54,103,199,1)", "rgba(54,165,199,1)", "rgba(54,199,180,1)"],
pointRadius: 15,
pointStyle: "cross",
pointHoverRadius: 25,
pointHoverBorderWidth: 3,
pointRotation: 45,
pointBorderWidth: 1.2,
backgroundColor: "rgba(61,49,225,0.5)",
borderColor: "rgba(61,49,225,1)",
label: "Averages",
fill: true
},
{
data: totals,
pointBackgroundColor: ["rgba(199,54,54,1)", "rgba(199,54,122,1)", "rgba(199,54,154,1)", "rgba(146,54,199,1)", "rgba(69,54,199,1)", "rgba(54,103,199,1)", "rgba(54,165,199,1)", "rgba(54,199,180,1)"],
pointBorderColor: ["rgba(199,54,54,1)", "rgba(199,54,122,1)", "rgba(199,54,154,1)", "rgba(146,54,199,1)", "rgba(69,54,199,1)", "rgba(54,103,199,1)", "rgba(54,165,199,1)", "rgba(54,199,180,1)"],
pointRadius: 15,
pointStyle: "cross",
pointHoverRadius: 25,
pointHoverBorderWidth: 3,
pointRotation: 45,
pointBorderWidth: 1.2,
backgroundColor: "rgba(225,49,52,0.35)",
borderColor: "rgba(225,49,52,1)",
label: "Totals",
fill: true
},
]
},
options: {
maintainAspectRation: false,
title: {
display: true,
text: chartTitle,
fontSize: 16
}
}
})
return chartDisplay;
}
var Chart = radarChart(["1","2","3","4"], [100,200,300,400], [10,20,30,40],
document.getElementById("radar-chart"), "TEST")
document.getElementById("radar-chart").innerHTML = Chart;
</script>
</body>
</html>
I am using the version 2.8, and i got the same problem, to fix
tooltips: {
enabled: true,
callbacks: {
label: function(tooltipItem, data) {
return data.datasets[tooltipItem.datasetIndex].label + ' : ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
}
}
}
See the issue
https://github.com/chartjs/Chart.js/issues/6188#issuecomment-497251833
I'm trying to plot a dataset into a chartJS line chart:
This is my data:
[{"close":0.00786609},{"close":0.00784},{"close":0.00784},
{"close":0.00780507},{"close":0.007816},{"close":0.00781599},
{"close":0.00780166},{"close":0.00778403},{"close":0.00782001},
{"close":0.0078},{"close":0.00778},{"close":0.007799},
{"close":0.00775057},{"close":0.0077688},{"close":0.00775001}]
This is my code:
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
datasets: [{
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: <%= JSON.stringify(prices) %>,
}]
},
// Configuration options go here
options: {}
});
How can I fix this?
You have configured your chart to be of type "line". The documentation for this type specifies that a dataset's data can be an Array of Numbers or an Array of Points, where a Point is an Object with a x property and a y property.
Your data is a JSON stringified Array of objects, each with a close property.
You need to map your prices Array into an Array of Numbers. In JavaScript, this could be done as:
prices.map(function (price) {
return price.close;
});
I have created a fiddle as an example.
I'm using Chart.js to create a line chart. I would like to have four different datasets that will all be visibile by default, but can be toggled on and off by clicking a button. How can this be achieved? I can't seem to find an answer in the documentation. .addData(), .removeData() and .update() all seem to be used for adding or removing values to existing datasets, but not adding or removing entire datasets. I would think this would be fairly commonly used feature but I can't find an answer anywhere.
After thoroughly researching this, there doesn't appear to be any built in function to toggle entire datasets. I used the .destroy() function to remove the entire existing chart, and then some logic to redraw it with the necessary datasets.
EDIT: Here's a fiddle with my full code if it's helpful to anyone -> http://jsfiddle.net/21xg27kr/4/
Here is a line chart with two datasets. By updating the datasets and calling the .update() method. The benefit here is you don't need to destroy the whole chart, and there is a nice animated transition which can be disabled.
TL:DR; solution on jsfiddle
Step by Step:
Bring in Chart.js from a CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
Create the HTML Canvas element that will hold the chart
<canvas id="line-chart"></canvas>
Hide/Show buttons for this example
Creating the chart, and the functions to update it live - notice that the same integer data needs to be copied in two places - in the initial creation, and in the show function.
<script>
lineChart = new Chart(document.getElementById("line-chart"), {
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [
{
label: "Set 1",
fill: true,
backgroundColor: "rgba(90,181,242,0.2)",
borderColor: "rgba(179,181,198,1)",
pointBorderColor: "#fff",
pointBackgroundColor: "rgba(179,181,198,1)",
data: [3, 1, 1, 0]
}, {
label: "Set 2",
fill: true,
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
pointBorderColor: "#fff",
pointBackgroundColor: "rgba(255,99,132,1)",
pointBorderColor: "#fff",
data: [1, 3, 3, 5]
}
]
},
options: {
title: {
display: true,
text: 'Chart Title'
}
}
});
function restoreLayer2(){
lineChart.data.datasets[1].data = [1, 3, 3, 5];
lineChart.update();
}
function removeLayer2() {
lineChart.data.datasets[1].data = [];
lineChart.update();
}
</script>