How do I mutate Chart.js data using React state? - javascript

In my project I wish to toggle between two sets of data: total hours worked each day in current week, and total hours worked each month in the current year. I am able to achieve Chart.js label manipulation in my button handlers, but I am unable to modify the state's data property. What am I missing here? Thank you for helping.
Note: The commented code produce this error statement when uncommented:
Uncaught TypeError: nextDatasets.map is not a function
LineChart.js
const [userData, setUserData] = useState({
labels: Object.keys(daysData),
datasets: [
{
label: "Hours worked",
data: Object.values(daysData),
backgroundColor: "red",
borderColor: "black",
borderWidth: 2,
},
],
});
const onShowWeeklyHandler = () => {
setUserData({ labels: Object.keys(daysData) });
// setUserData({ datasets: { data: Object.keys(daysData) } });
};
const onShowMonthlyHandler = () => {
setUserData({ labels: Object.keys(monthsData) });
// setUserData({ datasets: { data: Object.keys(monthsData) } });
};

You may be encountering issues because you are trying to shallow merge state with the useState hook. React does not support this. See this answer for more info.
If that does not solve your issue, have you looked into react-chartjs-2? You might be able to achieve what you want doing something like the following.
In your parent component (the one that contains the chart):
import { Bar } from "react-chartjs-2"; // import whatever chart type you need
...
const [userData, setUserData] = useState({
labels: Object.keys(daysData),
datasets: [
{
label: "Hours worked",
data: Object.values(daysData),
backgroundColor: "red",
borderColor: "black",
borderWidth: 2,
},
],
});
Then your handlers can be:
const onShowWeeklyHandler = () => {
setUserData({
...userData,
datasets: {
...userData.datasets,
labels: Object.keys(daysData),
data: Object.values(daysData),
},
});
};
const onShowMonthlyHandler = () => {
setUserData({
...userData,
datasets: {
...userData.datasets,
labels: Object.keys(monthsData),
data: Object.values(monthsData),
},
});
};
Finally:
return <Bar data={userData.datasets} />; // adapt for whatever chart type you need

Related

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

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>

charts js, doughnut chart not rendering tooptips correctly

i have a multilevel donut chart but it is not rendering correctly here is code
the problem is, onmouseover on all green parts it says objects, on all grey parts it says products, solution i would like is, on outer ring it should say products, in middle objects, and inner most should be materials, grey areas should just show number. here is a jsfiddle of the problem
Code:
var op=93;
var ap=99;
var mp=66;
var ctx = new Chart(myChart, {
type: 'doughnut',
data: {
labels: ['Objects', 'Products', 'Materials'],
datasets: [{
label: 'Objects',
data: [op, 100 - op],
backgroundColor: ['#006a4e','#eeeeee'],
hoverOffset: 4
},{
label: 'Products',
data: [ap, 100 - ap],
backgroundColor: ['#2e856e', '#eeeeee'],
hoverOffset: 4
},
{
label: 'Materials',
data: [mp, 100 - mp],
backgroundColor: ['#5ca08e', '#eeeeee'],
hoverOffset: 4
}
]
},
options: {
//cutoutPercentage: 40,
height: 200,
width:200
}
});
You can achieve that fairly simple with Chart.JS 2.7.2. Add labels to each dataset like this:
data: {
labels: ['Existing', 'Non'],
datasets: [
{
labels: ['Objects', 'Non-objects'],
...
}, {
labels: ['Products', 'Non-products'],
...
},
{
labels: ['Materials', 'Non-materials'],
...
}
]
}
And add the following label tooltip callback:
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ": " + dataset.data[index];
}
}
}
Demo: https://jsfiddle.net/adelriosantiago/fxd6vops/3/
I am sure it is possible with Chart.JS > 3.0 too but I have no idea how since quite a few things changed in the structure.
I had a same problem which took a lot of time but what worked in the end was importing these elements and initialising them ..
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
ChartJS.register(ArcElement, Tooltip, Legend);
these are the elements that helps make the entire chart. you can't skip them

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!

How to show bar labels in legend in Chart.js 2.1.6?

I'm creating charts using Chart.js and I want to show the labels for the bars in the legend, not the title of the dataset (there is only one), please see the below image as an example:
My current legend just looks like this:
I have looked through the docs but to no avail, I found them very confusing actually.
Here is my current code:
var chart_0 = new Chart($('#cp_chart_0'), {
type: 'bar'
, data: {
labels: ['Blue','Green','Yellow','Red','Purple','Orange']
, datasets: [{
label: 'Dataset 1'
, borderWidth: 0
, backgroundColor: ['#2C79C5','#7FA830','#7B57C3','#ED4D40','#EC802F','#1DC6D3']
, data: ['12','2','5','0','9','1']
}]
}
});
Thanks!
In one of the most recent releases of Chart.js 2.1.x, they added back this functionality. So go get the latest release first. Then insert the code below.
It is located under the options and legend. Here is how you use it:
options: {
legend: {
position: 'right'
}
}
Easiest way is to provide your data with multiple sets :
data: {
labels: ['total votes']
, datasets: [{
label: 'Blue'
, backgroundColor: ['#2C79C5']
, data: ['12']
},{
label: 'Green'
, backgroundColor: ['#7FA830']
, data: ['2']
},
...
]
}
But you can generate a custom labels using generateLabels - http://www.chartjs.org/docs/#chart-configuration-legend-configuration
Or even customise the whole legend, including formatting, with legendCallback - http://www.chartjs.org/docs/#chart-configuration-common-chart-configuration
This solution uses Chart.js version 3. You can pre-process your data using the Plugin Core API. The API offers different hooks that may be used for executing custom code.
I use the beforeInit hook to create individual datasets for each defined label/value pair. Note that the data of these new datasets are defined in point format (for instance [{ x: 1, y: 12 }]):
beforeInit: chart => {
let dataset = chart.config.data.datasets[0];
chart.config.data.datasets = chart.config.data.labels.map((l, i) => ({
label: l,
data: [{ x: i + 1, y: dataset.data[i] }],
backgroundColor: dataset.backgroundColor[i],
categoryPercentage: 1
}));
chart.config.data.labels = undefined;
}
Further you need to define a second x-axis that will contain the labels.
x1: {
offset: true,
gridLines: {
display: false
}
}
The labels on x1 need to be collected and defined programmatically each time the hidden state of a dataset changes. This can be done in the beforeLayout hook.
beforeLayout: chart => chart.options.scales.x1.labels = chart.config.data.datasets.filter((ds, i) => !chart.getDatasetMeta(i).hidden).map(ds => ds.label)
Please take a look at below runnable code and see how it works.
new Chart('chart', {
type: 'bar',
plugins: [{
beforeInit: chart => {
let dataset = chart.config.data.datasets[0];
chart.config.data.datasets = chart.config.data.labels.map((l, i) => ({
label: l,
data: [{ x: i + 1, y: dataset.data[i] }],
backgroundColor: dataset.backgroundColor[i],
categoryPercentage: 1
}));
chart.config.data.labels = undefined;
},
beforeLayout: chart => chart.options.scales.x1.labels = chart.config.data.datasets.filter((ds, i) => !chart.getDatasetMeta(i).hidden).map(ds => ds.label)
}],
data: {
labels: ['Blue', 'Green', 'Yellow', 'Red', 'Purple', 'Orange'],
datasets: [{
data: ['12', '2', '5', '0', '9', '1'],
backgroundColor: ['#2C79C5', '#7FA830', '#FFF200', '#ED4D40', '#800080', '#EC802F']
}]
},
options: {
interaction: {
intersect: true,
mode: 'nearest'
},
plugins: {
legend: {
position: 'right'
},
tooltip: {
callbacks: {
title: () => undefined
}
}
},
scales: {
y: {
beginAtZero: true
},
x: {
display: false
},
x1: {
offset: true,
gridLines: {
display: false
}
}
}
}
});
canvas {
max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.0/chart.min.js"></script>
<canvas id="chart" height="120"></canvas>

Categories

Resources