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
- How can I make line on chart thinner?
- Loading an external JSON into ChartJs
- Move chart x axis label and borders
- How to update chart.js in vue
- Chart.js v2 is there a way to draw bar chart horizontally?
- How to assign different background colors to chart.js pie chart data set?
- chart.js onClick event function, access angular component
- Charts JS: How to set units?
- Angular 4:PrimeNg DoughnutChart dynamic data issue.
- How to add dataset legend in chartjs tooltip
- Chart.js using json data from MySQL
- How can I export data from a csv file or excel file to a javascript object?
- Chart.JS canvas gets larger every time drawn
- How do I change the grid line style on the Y axis in Chart.js?
- ChartJS rotate 90' but keep text straight
- how to format date string for x axis labels in chartjs?
- Pass custom labels as an array to Chart JS Tool tip
- Why doesn't my donut chart, created with Chart.js, appear?
- ChartJS plotting x/y in a line chart
- Chart.js not showing dynamically populated data
- Chart.js: Display Custom Tooltips, always visible on stacked bar-chart
- ng2-Chart: can we show the tooltip data of pie chart on load?
- ChartJS with React: Only one value showing on time chart
- How can I merge multiple HTTP calls to one entity model in Angular
- Horizontal Bar-Chart - angular-chart.js
- Pie chart not working using angular and ng2-charts
- On click event to show name of pie chart slice in chartsJS
- Use Google Spreadsheet as data source for Chart.js
- Multiple usage of Javascript function
- Angular 2 ng2-charts donut change segment color