How to set action on slice-click Doughnut in Chart.js - javascript

I've been trying to add chart.js to my Django Project, which worked pretty fine so far. I made a doughnut-chart with two slices. Now i want to have each of those slices to have seperate actions on click, like for example redirecting to new side.
These are my chart settings:
var config = {
type: 'doughnut',
data: {
datasets: [{
data: {{ data|safe }}, // Error because django and js are being mixed
backgroundColor: [
'#ff0000', '#008000'
],
label: 'Population'
}],
labels: {{ labels|safe }}
},
options: {
responsive: true
}
};
And this is the rendering and my function to make the actions on click:
window.onload = function() {
var ctx = document.getElementById('pie-chart').getContext('2d');
var myPieChart = new Chart(ctx, config);
$('#myChart').on('click', function(event) {
var activePoints = myPieChart.getElementsAtEvent(event)
if(activePoints[0]){
console.log("Helo 1")
}
else {
console.log("helo 2")
}
})
};
I saw my solution on other pages, but it doesn't work at all. Am I missing something? If yes could you please help?

getElementAtEvent has been replaced with chart.getElementsAtEventForMode in Chart.js v3 (see 3.x Migration Guide).
Please take a look at below runnable code and see how it works now:
const pieChart = new Chart("myChart", {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow"],
datasets: [{
data: [8, 5, 6],
backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"],
}]
},
options: {
onClick: evt => {
var elements = pieChart.getElementsAtEventForMode(evt, 'index', { intersect: true }, false);
var index = elements[0].index;
console.log(pieChart.data.labels[index] + ': ' + pieChart.data.datasets[0].data[index]);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<canvas id="myChart"></canvas>

Related

Chart JS Displays Only Bigger Dataset But Has Both Datasets?

fairly new to JS and I have a strange issue with chart JS bar chart.
<script>
$(document).ready(function() {
var bar = document.getElementById("chart-bar-11").getContext('2d');
var data1 = {
labels: ["Yesterday"],
datasets: [{
label: "Win",
data: [{{ gam }}],
borderColor: '#4099ff',
backgroundColor: '#4099ff',
hoverborderColor:'#4099ff',
hoverBackgroundColor: '#4099ff',
}, {
label: "Lose",
data: [{{ results }}],
borderColor: '#0e9e4a',
backgroundColor: '#0e9e4a',
hoverborderColor:'#0e9e4a',
hoverBackgroundColor: '#0e9e4a',
}]
};
var myBarChart = new Chart(bar, {
type: 'bar',
data: data1,
options: {
barValueSpacing: 20
}
});
});
</script>
I have a simplke bar chart, but here is a screen shot of current behavior, super confused how this chart shows it has both datasets but will only display the larger dataset?
Ended up finding the options needed in another Chart JS post, this is what I was missing.
var myBarChart = new Chart(bar, {
type: 'bar',
data: data1,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
It appears he "beginAtZero" is what was missing. This now works as expected.

How can I display the xAxes and yAxes data in the tooltip, Chart JS?

I am trying to achieve the Tooltip shown below in the first image. Inside of the tooltip I need to display the yAxes and xAxes data. The chart.js version I am using is 3.7.0
My tooltip looks like this:
The tooltip that I am trying copy:
The chart.js documentation is quite hard for me to understand. Is there any guru that can explain to me.
Question: Why is my tooltip returning the yAxes data, that I return as a variable(label) as undefined?
Are there any other options I can use to make my chart look like the chart in the second picture?
My Code:
tooltip: {
displayColors: false,
backgroundColor: 'rgba(45,132,180,0.8)',
bodyFontColor: 'rgb(255,255,255)',
callbacks: {
title: function(item, everything){
return;
},
label: function(item, everything){
//console.log(item);
//console.log(everything);
let first = item.yLabel;
let second = item.xLabel;
let label = first + ' ppm';
return label;
}
}
}
Thank you in advance for your time and efforts, please help me figure out what am I doing wrong!
yLabel and xLabel dont exist anymore on the tooltip, they are V2 syntax.
You can just axess the y object in the parsed section to get the y value. Then you can use the afterBody callback to show the x label like so:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
}]
},
options: {
plugins: {
tooltip: {
displayColors: false,
backgroundColor: 'rgba(45,132,180,0.8)',
bodyFontColor: 'rgb(255,255,255)',
callbacks: {
title: () => {
return
},
label: (ttItem) => (`${ttItem.parsed.y} ppm`),
afterBody: (ttItems) => (ttItems[0].label)
}
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>

How to add text to chart.js data?

I need help to add a text after the data that shows the graph, the code I have is the following:
var ctx = document.getElementById("chart-area");
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["label1", "label2", "label3", "label4"],
datasets: [{
data: [ 10, 20, 30, 40 ]
}]
}
}
It shows me the information like this:
label1: 10
But i need to add text after that, something like:
label1: 10 Mb
Please, I don't know how to add it, I already tried several ways
ChartJs does not provide any format label feature you have to play with it.
Initialize chart configuration with empty array then update it when you pushing data.
From this reference https://github.com/chartjs/Chart.js/issues/2738
here is fiddle link: http://jsfiddle.net/qsnpsxz5/7/
chart.config.data.labels.push("A label");
chart.config.data.labels.push("A label2");
chart.config.data.datasets[0].data.push(10);
chart.config.data.datasets[0].data.push(20);
chart.update();
Try using this script
var ctx = document.getElementById("chart-area");
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["label1", "label2", "label3", "label4"],
datasets: [
{ data: [ 10, 20, 30, 40 ] }
]
},
options: {
tooltips: {
enabled: true,
callbacks: {
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label;
var val = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return label + ' : ' + val + ' Mb';
}
}
}
}
});

Pushing data from json to Chart.js labels and data

I am using the Chart.js lib to make charts.
I have a json array that I am getting from a database.
Here is the console log of it: Data
I need to get the address, speed, and speed limit for every element in the list and use it in a chart.
My current code is as follows:
function ShowChart() {
var popCanvas = document.getElementById("speedLimitsChart");
console.dir(speeddata);
var labels = speeddata.map(function (e) {
return e.Adress;
});
var speed = speeddata.map(function (e) {
return e.Speed;
});
var speedlimits = speeddata.map(function (e) {
return e.SpeedLimits;
});
console.dir(labels);
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
labels: labels
});
}
But in the result I only have the first element in my chart, and there are no labels.
Here is the output screen: Chart
I checked speed, speedlimits and labels and all of them have 2 elements. Can you please advise where my problem might be?
I found where is my problem
I need to write labels inside of data
Like this
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
labels: labels ,
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
});

Show the latest labels in a bar chart with React.js using react-chartjs

I am working on creating a bar chart in React.js using react-chartjs library. I am able to get the bar chart to display but since my data is huge and it is collected for every 10 seconds. The bar chart displays something like
My dataset for it looks like
var loadData = [{
options: {
elements: {
rectangle: {
borderWidth: 2,
borderColor: 'rgb(0, 255, 0)',
borderSkipped: 'bottom'
}
},
responsive: true,
legend: {
position: 'top'
},
title: {
display: true,
text: 'ETL Load Chart'
},
scales: {
xAxes: [{
type: 'time',
ticks: {
autoSkip:true,
maxTicksLimit:20
}
}]
}
},
data: {
labels: [],
datasets: [
{
backgroundColor: "rgba(220,220,220,0.5)",
data: []
}
]
}
}]
I am updating the the data with the help of a library immutability-helpers
case 'GET_LOAD_DATA_RECEIVED':
var payload = action.data.payload
var dataValues = [], labelValues = [];
payload.forEach(function(item){
dataValues.push(parseInt(item['recs_upd']) + 1);
labelValues.push(item['from_ts']);
})
return update(state, {
0: {
data: {
labels: {
$push: labelValues
},
datasets: {
0: {
data: {
$push: dataValues
}
}
}
}
}
})
break;
and I am calling the rendering of Chart like
<Bar data={this.props.loadInfo[0].data} options={this.props.loadInfo[0].options} width="600" height="250" />
I am using "react-chartjs": "^0.8.0", and "chart.js": "^1.1.1" I couldn't update to 2.0 in chart.js were I saw something called showXlabels being present since react-chartjs supports the current version.
Thanks for any help.
Pass only the latest n number of data for every 10 seconds.
const updatedData = {...this.props.loadInfo[0]}
const newData = {
data: {
labels: [...updatedData.labels].reverse().slice(0, 30).reverse(),
datasets: [...updatedData.datasets].reverse().slice(0, 30).reverse(),
}
}
const newLimitedData = {...updatedData, ...newData }
<Bar data={newLimitedData.data} options={newLimitedData.options} width="600" height="250" />
Hope this helps!

Categories

Resources