score:22
if you need to show/hide charts selecting/unselecting all labels here is an example:
var barchartdata = {
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32],
datasets: [{
label: 'one',
backgroundcolor: 'rgba(206, 0, 23, 1)',
data: [0, 1, 3, 0, 2, 0, 0, 2, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 2, 1, 0, 1, 2, 1, 1, 0, 0, 0, 2, 2, 0, 3]
}, {
label: 'two',
backgroundcolor: 'rgba(206, 0, 23, 0.75)',
data: [0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1]
}, {
label: 'three',
backgroundcolor: 'rgba(206, 0, 23, 0.5)',
data: [0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 2, 0, 0, 0, 1, 0, 0, 0, 0, 1]
}]
};
var ctx = document.getelementbyid('canvas').getcontext('2d');
var chartinstance = new chart(ctx, {
type: 'bar',
data: barchartdata,
options: {
title: {
display: false,
},
responsive: true,
scales: {
xaxes: [{
stacked: true,
}],
yaxes: [{
stacked: true
}]
}
}
});
$("#toggle").click(function() {
chartinstance.data.datasets.foreach(function(ds) {
ds.hidden = !ds.hidden;
});
chartinstance.update();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.7.2/chart.bundle.min.js"></script>
<button id="toggle">show/hide all</button>
<canvas id="canvas" height="500" width="800"></canvas>
jsfiddle: https://jsfiddle.net/beaver71/00q06vjp/
credits: see https://github.com/chartjs/chart.js/issues/3009
update: for pie chart use "meta", see: https://jsfiddle.net/beaver71/u0y0919b/
score:0
the correct answer result in :
chart.data.datasets.foreach((obj, index) => {
let meta = this.eval_chart.getdatasetmeta(index);
meta.hidden = !meta.hidden || null;
});
chart.update();
as wrote in the documentation : https://www.chartjs.org/docs/latest/configuration/legend.html#custom-on-click-actions
score:1
v3 answer
you can use a custom generatelabels
function together with a custom onclick
to get it as an extra legenditem like so:
const defaultlegendclickhandler = chart.defaults.plugins.legend.onclick;
const piedoughnutlegendclickhandler = chart.controllers.doughnut.overrides.plugins.legend.onclick;
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'
},
{
label: '# of points',
data: [7, 11, 5, 8, 3, 7],
bordercolor: 'orange'
}
]
},
options: {
plugins: {
legend: {
onclick: (evt, legenditem, legend) => {
const type = legend.chart.config.type;
let alllegenditemsstate = [];
if (legenditem.text === 'hide all datasets' || legenditem.text === 'show all datasets') {
if (typeof legend.hideall === 'undefined') {
legend.hideall = false;
}
legend.chart.data.datasets.foreach((dataset, i) => {
legend.chart.setdatasetvisibility(i, legend.hideall)
});
legend.hideall = !legend.hideall;
legend.chart.update();
return;
}
if (type === 'pie' || type === 'doughnut') {
piedoughnutlegendclickhandler(evt, legenditem, legend)
} else {
defaultlegendclickhandler(evt, legenditem, legend);
}
alllegenditemsstate = legend.chart.data.datasets.map((e, i) => (legend.chart.getdatasetmeta(i).hidden));
if (alllegenditemsstate.every(el => !el)) {
legend.hideall = false;
legend.chart.update();
} else if (alllegenditemsstate.every(el => el)) {
legend.hideall = true;
legend.chart.update();
}
},
labels: {
generatelabels: (chart) => {
const datasets = chart.data.datasets;
const {
labels: {
usepointstyle,
pointstyle,
textalign,
color
}
} = chart.legend.options;
const legenditems = chart._getsorteddatasetmetas().map((meta) => {
const style = meta.controller.getstyle(usepointstyle ? 0 : undefined);
return {
text: datasets[meta.index].label,
fillstyle: style.backgroundcolor,
fontcolor: color,
hidden: !meta.visible,
linecap: style.bordercapstyle,
linedash: style.borderdash,
linedashoffset: style.borderdashoffset,
linejoin: style.borderjoinstyle,
strokestyle: style.bordercolor,
pointstyle: pointstyle || style.pointstyle,
rotation: style.rotation,
textalign: textalign || style.textalign,
datasetindex: meta.index
};
});
legenditems.push({
text: (!chart.legend.hideall || typeof chart.legend.hideall === 'undefined') ? 'hide all datasets' : 'show all datasets',
fontcolor: color,
fillstyle: 'turquoise', // box color
strokestyle: 'turquoise', // linecollor around box
});
return legenditems;
}
}
}
}
}
}
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.6.0/chart.js"></script>
</body>
score:2
for chartjs 2.9.3, this works as requested by david in the comments:
const chart = ...
chart.data.datasets.foreach(dataset => {
object.keys(dataset._meta).foreach(key => {
const current = !dataset._meta[key].hidden
dataset._meta[key].hidden = current || null
})
})
chart.update()
toggles all with a button, while playing nicely with the individual toggling in the chart legend.
Source: stackoverflow.com
Related Query
- Select All and Unselect Option for chart.js
- How can labels/legends be added for all chart types in chart.js (chartjs.org)?
- How to add second Y-axis for Bar and Line chart in Chart.js?
- Problem for display a chart with Chart.js and Angular
- How to hide the y axis and x axis line and label in my bar chart for chart.js
- How to create a chart that uses strings for both the X and Y axes?
- How to draw outer labels for polar chart using ng2-charts and chart.js at fixed positions outside the rings?
- Setting Common labels and background color common for all the charts in ChartJs
- How to wait for all items to load within ng-repeat before then rendering a chart for each item
- How do I customize y-axis labels and randomly pick the value from the data range for x-axis in Chart js
- How can I have different values for the chart and the tooltip in chart.js?
- Click on interactive chart.js bar chart and get value for labels and groups in JS
- Javascript and Chart.JS - issue with getting unique text in 3 donut hole charts - same text showing for all 3 donut holes
- How do you set x and y axis and Title for a line chart using charts.js?
- how to reduce list chart to one and use select dropdown to show selection without refresh page?
- How to remove all gridlines and ticks all lines in lines chart in javascript taken from cdn)
- Charts JS: Doughnut chart and hiding tooltip for specific data index within each dataset
- How remove duplicates xAxis labels and show all values on chart
- attempting to change height and width of canvas for chart
- ChartJS: Show all tooltips with Total for Multi Pie chart
- getting additional value fields from data source for dx.chartjs doughnut chart
- I am using chart js to draw a chart. I did everything right but i don't know why the x axis and y axis label is not comming in chart. code below
- Frontend and backend for chart using chartjs, mongodb, and controller
- Line chart plotting multiple points for duplicate data on x and y axis using chart.js
- Chart.JS Get Json data for chart and return dataset where a type equals a certain type
- Chart js pie chart, darker shade for higher value and lighter shade for lower value. I'm displaying values monthly
- Chart JS: Donut/Doughnut Chart: Tooltip to be shown always for all the data. All tooltip is not shown when multiple data are with 0 data
- Initializing Chart Js Multiple times for and Array of Objects
- No chart display for Chart.js and JSON data
- how to create bar chart with group and sam color for each group using chart.js?
More Query from same tag
- Chart.js loading data colors from PHP
- Add dynamically function to Chart.js
- Chart.js - Give specific circles a background color in a bubble chart
- Django chartjs multiple charts stacked
- React-Chart-JS-2 ^3.0.5 | TypeError: Cannot read properties of undefined (reading 'visible') at Chart._getSortedDatasetMetas
- Doughnut Chart not displaying data with Chart Js and Backbone js
- Chart.js - Make x-axis grouped by day
- Chart.js - How does it calculate Y-Axis on bar chart?
- Displaying mixed types of legends (bar and lines) with Chartjs
- How to display large amount of information properly without cramping too much in Chart.js
- Create Line Chart and populate with database information
- ChartJS set default axis
- In chart.js, Is it possible to hide x-axis label/text of bar chart if accessing from mobile?
- angular directive is not working with chartjs
- Chart.js - Line Chart format data to Lacs/Crores
- Chart.js scale which increases by x (arbitary number) for each tick
- ngx-charts-advanced-pie-chart is reading my rest api response as null
- How do you set pie chart colors in angular-chart.js
- Cant change labels in Chart.js 2.0 Beta
- Chart.js showing x-axis ticks even though set to false
- Realtime chart JS in Java obtaining the data from a sensor ;Chart.js: Failed to create chart: can't acquire context from the given item
- Implement a cash flow timeline
- Chart.js maxBarThickness is deprecated in angular 8
- How to align ticks label in chartJS 3.x?
- how to show data label on barchart using chart.js in Angular10 project?
- How to destroy chart object in order to change chart data dynamically (Chart.js)?
- Extend bar chart on Chart JS 2 into a new type of Chart
- How to reorganize data to display how many times a string appears in an array object?
- How to achive Chart JS weather chart of 5 day / 3 hour forecast data
- Chart JS not working with date