ChartJS Pie Chart How default just show 2 legend datas - javascript

I want to show 10 data in a pie chart, but only show 2 of them.
my version is v2.8.0
chart.getDatasetMeta(i).hidden=true;
this is work in bar charts, but not work in pie.
var donutOptions = {...}
var donutChartCanvas = $(pieChart).get(0).getContext(2d);
var donutData = {
labels: [],
texts: [],
datasets: [
{
data: [ ],
backgroundColor : []
}
]
};
var donutChart = new Chart(donutChartCanvas, {
plugins: [ChartDataLabels],
type: doughnut,
data: donutData,
options: donutOptions
});
getDatasetMeta undefined.
now is:
I want to this:

I find a work way, try it.
add
legend : {
}
into option
var donutOptions = {
maintainAspectRatio : false,
responsive : true,
animation: {
animateScale: true,
animateRotate: true
},
tooltips: {
intersect: false,
callbacks: {
label: function (tooltipItem, data) {
...
}
},
},
plugins: {
datalabels: {
...
},
},
},
legend : {
}
};
and use this
donutChart.chart.getDatasetMeta(0).data[index].hidden = true;
donutChart.update();

Related

How can I move text around on a pie chart in ChartJS?

Wondering how I can move the text more to the left and create a new line between the labels. As you can see the "label" and "percentage" are on top of each other.
I'm using ChartJS v2.8.0 and ChartJS Plugin Labels 1.1.0
Current Look:
Desired Look:
Current code:
var chart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['T-Shirts', 'Sweaters'],
datasets: [{
backgroundColor: [$('#chart-color-1').val(), $('#chart-color-2').val()],
data: [$('#attire_1_percent').val(), $('#attire_2_percent').val()],
borderWidth: 0
}]
},
options: {
maintainAspectRatio: false,
legend: {
display: false
},
plugins: {
labels: [{
render: "label",
fontColor: '#fff',
},
{
render: 'percentage',
fontColor: '#fff',
}
],
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return data.labels[tooltipItem.index] + ": " + data.datasets[0].data[tooltipItem.index] + "%"
}
},
},
}
});

Chart.js: how to order the tool tips in the graph

I generate a graph where I have 3 groups of data:
bottom
middle
top
Each bar has the top values at the top of the bar, then the middle value and then the bottom value.
When Chart.js displays the tooltip, I have first the bottom value, then the middle and the the top. So, it is the opposite of the order in the bar.
To display the values I added this code
var stackedBarChartOptions = {
responsive: true,
maintainAspectRatio: false,
tooltips: {
mode: 'label',
callbacks: {
label: function (tooltipItem, data) {
return data.datasets[tooltipItem.datasetIndex].label + ": " +
tooltipItem.yLabel;
}
}
}
}
Is it possible to order the list of tool tips?
in the tooltip label callback, we can choose any index to display.
in your callback, you're displaying the index passed to the callback.
tooltipItem.datasetIndex
instead, let's display the reverse order...
data.datasets.length - 1 - tooltipItem.datasetIndex
but we will also have to add the callback for labelColor,
to display the correct color box for the specific label.
see following working snippet...
var chart_canvas = document.getElementById('myChart');
var stackedLine = new Chart(chart_canvas, {
type: 'bar',
data: {
labels: ['A'],
fill: true,
datasets: [
{
label: 'Low',
data: [67.8],
backgroundColor: '#D6E9C6'
},
{
label: 'Moderate',
data: [20.7],
backgroundColor: '#FAEBCC'
},
{
label: 'High',
data: [11.4],
backgroundColor: '#EBCCD1'
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
tooltips: {
mode: 'label',
callbacks: {
labelColor: function (tooltipItem, data) {
return {backgroundColor: data.data.datasets[data.data.datasets.length - 1 - tooltipItem.datasetIndex].backgroundColor};
},
label: function (tooltipItem, data) {
return data.datasets[data.datasets.length - 1 - tooltipItem.datasetIndex].label + ": " + data.datasets[data.datasets.length - 1 - tooltipItem.datasetIndex].data[tooltipItem.index];
}
}
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

How to set the size of the arc in ChartJS?

I can’t set the arc size for the chart. How to set the size of the arc? Also, I can’t make the animation work, although I took an example from the official documentation :/
Here is my code:
var ctx = document.getElementById('myChart-<%= ChartId %>').getContext('2d');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [{
data: [
11,69,20
],
backgroundColor: [
"#ffb74d",
"#4db6ac",
"#bf360c"
]
}]
},
options: {
tooltips: {
enabled: false
},
plugins: {
labels: {
render: 'percentage',
precision: 2,
showZero: true,
fontSize: 30,
fontColor: ['#2c405a', '#2c405a', 'white'],
fontFamily: "PTSansBold",
}
},
animation: {
duration:5000
}
}
});
According to Config Options, cutoutPercentage defines the percentage of the chart that is cut out of the middle. To also make animation work, place the canvas inside a div and add responsive: true to your options.
options: {
responsive: true,
cutoutPercentage: 30,
...
}
The animations works fine with what you defined in your options.
var myChart = new Chart(document.getElementById('myChart'), {
type: 'doughnut',
data: {
datasets: [{
data: [
11,69,20
],
backgroundColor: [
"#ffb74d",
"#4db6ac",
"#bf360c"
]
}]
},
options: {
responsive:true,
cutoutPercentage: 60,
tooltips: {
enabled: false
},
plugins: {
labels: {
render: 'percentage',
precision: 2,
showZero: true,
fontSize: 30,
fontColor: ['#2c405a', '#2c405a', 'white'],
fontFamily: "PTSansBold",
}
},
animation: {
duration: 5000
}
}
});
div {
width: 300px;
height: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<div>
<canvas id="myChart"></canvas>
</div>
The doughnut/pie chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset.
For example, if you want to change the width of the border there is an option of cutoutPercentage.
options: {
cutoutPercentage: 80,
...
}
Similarly, you can find other options from the official documentation.
https://www.chartjs.org/docs/latest/charts/doughnut.html
var ctx = document.getElementById('chart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [{
data: [
11,69,20
],
backgroundColor: [
"#ffb74d",
"#4db6ac",
"#bf360c"
]
}]
},
options: {
cutoutPercentage: 80,
animation: {
duration:5000
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart"></canvas>
I hope this helps. Please let me know if you have any doubt.
if anyone looking for fix as per chartJS 3 and year-2022
they have changes some configurations and this will work as follow
options: {
cutout: 80,
...
}

Horizontal chart label using Vue-chart.js

I have developed a horizontal Bar chart using Vue-chart.js, all the data and labels are coming from API. The problem is that the value is also visible along with the label, How can I hide the value appearing beside the label? The image is given below
I have the following code.
import { HorizontalBar } from 'vue-chartjs'
export default {
name: 'diagram',
extends: HorizontalBar,
data: () => ({
chartData: '',
score: {},
value: [],
keys: [],
options: {
scales: {
xAxes: [{
ticks: {
scaleShowLabels:false,
}
}],
yAxes: [{
ticks: {
scaleShowLabels:false,
mirror: true
}
}]
},
responsive: true,
},
responsive: true,
maintainAspectRatio: false
}),
created () {
// Overwriting base render method with actual data.
this.$http({
method: 'get',
url: this.base_url + '/exam/api/score/' + this.$store.state.user.id + '/',
auth: {
username: 'my-username',
password: 'my-password'
},
}).then(res => {
console.log(res);
if (res.status == '200') {
console.log(res.data);
this.score = res.data;
for (let v in this.score) {
this.value.push(this.score[v]);
}
for (let key in this.score) {
this.keys.push(key);
}
}
});
this.fillData()
},
mounted(){
this.renderChart(this.chartData, this.options);
},
methods: {
fillData () {
this.chartData = {
labels: this.keys,
datasets: [
{
fillColor: "#ffecbf",
strokeColor: "#dacdd2",
data: this.value,
}
],
}
}
},
watch: {
data: function () {
this._chart.destroy();
this.renderChart(this.chartData, this.options);
},
},
}
please help me out. Thanks in advance.

Changing yAxis and plotOptions for drilldown

I am using HighCharts to visualize percentages from projects, which are downdrilled into variables which make the percentages!
I will give my code :
$(function () {
// Create the chart
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Comparison'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
enabled: true,
text: 'Percentages',
style: {
fontWeight: 'normal'
}
},
labels: {
format: '{value}%'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: [{
name: '',
colorByPoint: true,
data: []
}],
credits: {
enabled: false
},
drilldown: {
series: [{
name : '',
id: '',
data: []
}]
}
};
$.getJSON('/uploads/fraction.json', function (list) {
options.series = list;
});
$.getJSON('/uploads/drilldown.json', function (list2) {
options.drilldown.series = list2;
var chart = new Highcharts.Chart(options);
});
});
Example of the JSONs:
fraction.json
[{"name":"","colorByPoint":true,"data":[{"name":1,"y":80,"drilldown":1},{"name":2,"y":87,"drilldown":2},{"name":3,"y":105.71428571429,"drilldown":3},{"name":5,"y":"","drilldown":5},{"name":6,"y":53.160248409091,"drilldown":6}]}]
drilldown.json
[{"name":1,"id":1,"data":[["Total",2],["Estimated",2.5]]},{"name":2,"id":2,"data":[["Total",3.9],["Estimated",4.5]]},{"name":3,"id":3,"data":[["Total",3.7],["Estimated",3.5]]},{"name":5,"id":5,"data":[["Total",""],["Estimated",0.44]]},{"name":6,"id":6,"data":[["Total",0.233905093],["Estimated",0.44]]}]
I would like the graph to show percentages above the column and on the yAxis when the graph is first loaded, but absolute values when the drilldown is activated. I didn't manage to get it until now. Could you help me?
There are two ways of doing those changes - a static and dynamic way. Static way - define data labels and tooltip options for drilldown series.
Dynamic way - apply the options on drilldown/drillup events.
events: {
drilldown: function(options) {
this.yAxis[0].update({
labels: {
format: '{value}'
}
}, false, false);
options.seriesOptions.dataLabels = {
format: '{point.y:.1f}'
};
options.seriesOptions.tooltip = {
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}</b> of total<br/>'
};
},
drillup: function () {
this.yAxis[0].update({
labels: {
format: '{value}%'
}
}, false, false);
}
}
example: http://jsfiddle.net/d4fmaeea/
Two warnings:
In your json files, you have points which has value equals to "" which is not a valid type (must be number/null) and it may cause some issues, e.g. column with value 0 will have the same height as the column with value 10.
$.getJSON() is an asynchronous function. You use getJSON to assign list to options.series but that part may be executed after the chart was created so you would end up with the chart with no top-level series, only the drilldown ones.
Async part of code:
$.getJSON('/uploads/fraction.json', function (list) {
options.series = list;
});
$.getJSON('/uploads/drilldown.json', function (list2) {
options.drilldown.series = list2;
var chart = new Highcharts.Chart(options);
});

Categories