Displaying labels on a Doughnut Chart using Chart.js - javascript

I am really stuck at the moment.
Using Chart.js v3.2.1 to display some charts, which were working great.
Then when I attempted use the chartjs-plugin-datalabels plugin to display labels on a Doughnut chart, that chart no longer displays.
I can't see what I've done wrong. I'm in need of help!
Note: There are a lot of questions similar to this on Google and Stackoverflow but most of them are about previous versions, but my work has only approved for me to be working with the lastst version of Chart.JS.
//DOUGHNUT GRAPH
var doughnutChartData = {
labels: [
'Dr # Fault',
'TP # Fault',
'Wthr Evt',
'Other'
],
datasets: [
{
label: "slices",
borderWidth: 3,
data: [2,3,2,1],
backgroundColor: [
'#D6001C',
'#00A3E0',
'#52A886',
'#2E3138'
],
borderColor: [
'#fff',
'#fff',
'#fff',
'#fff'
]
}
]
};
//DOUGHNUT CHART OPTIONS
var doughnutChartOptions = {
responsive: true,
plugins: {
datalabels: {
formatter: function (value, context) {
return context.chart.data.labels[
context.dataIndex
];
},
},
title: {
display: true,
text: "Reported Fault Allocation",
color: "#D6001C",
font: {
family: "AvenirNextLTW01-Regular",
size: 16,
style: 'normal'
}
},
legend: {
display: false
}
},
scales: {
x: {
grid: {
display: false,
drawBorder: true
}
},
y: {
grid: {
display: true,
drawBorder: true,
},
},
},
elements: {
point: {
radius: 0
}
},
}
//DISPLAY DOUGHNUT GRAPH
var ctx = document.getElementById("canvas3-detailed").getContext("2d");
window.myDoughnut = new Chart(ctx, {
plugins: [ChartDataLabels],
type: "doughnut",
data: doughnutChartData,
options: doughnutChartOptions
});
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2"></script>
<canvas id="canvas3-detailed"></canvas>

The link for your Plugin is broken. You need to remove #2 from the end:
https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels
There is also the not defined error because you reference ChartDataLabels which has not been declared. You need to put it in a string:
//DOUGHNUT GRAPH
var doughnutChartData = {
labels: [
'Dr # Fault',
'TP # Fault',
'Wthr Evt',
'Other'
],
datasets: [
{
label: "slices",
borderWidth: 3,
data: [2,3,2,1],
backgroundColor: [
'#D6001C',
'#00A3E0',
'#52A886',
'#2E3138'
],
borderColor: [
'#fff',
'#fff',
'#fff',
'#fff'
]
}
]
};
//DOUGHNUT CHART OPTIONS
var doughnutChartOptions = {
responsive: true,
plugins: {
datalabels: {
formatter: function (value, context) {
return context.chart.data.labels[
context.dataIndex
];
},
},
title: {
display: true,
text: "Reported Fault Allocation",
color: "#D6001C",
font: {
family: "AvenirNextLTW01-Regular",
size: 16,
style: 'normal'
}
},
legend: {
display: false
}
},
scales: {
x: {
grid: {
display: false,
drawBorder: true
}
},
y: {
grid: {
display: true,
drawBorder: true,
},
},
},
elements: {
point: {
radius: 0
}
},
}
//DISPLAY DOUGHNUT GRAPH
var ctx = document.getElementById("canvas3-detailed").getContext("2d");
window.myDoughnut = new Chart(ctx, {
plugins: ["ChartDataLabels"],
type: "doughnut",
data: doughnutChartData,
options: doughnutChartOptions
});
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="canvas3-detailed"></canvas>

I found out that the version of the plugin I used was incorrect. I have now updated and it is displaying with labels!
//DOUGHNUT GRAPH
var doughnutChartData = {
labels: [
'Dr # Fault',
'TP # Fault',
'Wthr Evt',
'Other'
],
datasets: [{
label: "slices",
borderWidth: 3,
data: [2, 3, 2, 1],
backgroundColor: [
'#D6001C',
'#00A3E0',
'#52A886',
'#2E3138'
],
borderColor: [
'#fff',
'#fff',
'#fff',
'#fff'
]
}]
};
//DOUGHNUT CHART OPTIONS
var doughnutChartOptions = {
responsive: true,
plugins: {
datalabels: {
color: 'white',
formatter: function (value, context) {
return context.chart.data.labels[
context.dataIndex
];
},
},
title: {
display: true,
text: "Reported Fault Allocation",
color: "#D6001C",
font: {
family: "AvenirNextLTW01-Regular",
size: 16,
style: 'normal'
}
},
legend: {
display: false
}
},
scales: {
x: {
grid: {
display: false,
drawBorder: true
}
},
y: {
grid: {
display: true,
drawBorder: true,
},
},
},
elements: {
point: {
radius: 0
}
},
}
//DISPLAY DOUGHNUT GRAPH
var ctx = document.getElementById("canvas3-detailed").getContext("2d");
window.myDoughnut = new Chart(ctx, {
plugins: [ChartDataLabels],
type: "doughnut",
data: doughnutChartData,
options: doughnutChartOptions
});
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0-rc"></script>
<canvas id="canvas3-detailed"></canvas>

Related

Show x axis label on top of stacked bar and custom tooltip on chart js

I want to show the total value and x axis label on top of my stacked bar chart so it look like this
but right now, i'm only can show the total value, i don't know how to add the x axis label, so far mine look like this
i'm also want to custom my tooltip to look like this
Here's my code:
export default {
name: 'BarAllYear',
data() {
return {
BarAllYearData,
};
},
mounted() {
const ctx = document.getElementById('bar-all-year').getContext('2d');
const BarChart = {
type: 'bar',
data: this.BarAllYearData,
plugins: [ChartDataLabels],
options: {
borderWidth: 1,
responsive: true,
plugins: {
legend: {
display: false,
},
tooltip: {
xAlign: 'center',
yAlign: 'bottom',
backgroundColor: '#FFF',
displayColors: false,
titleFont: {
size: 20,
},
bodyFont: {
size: 18,
},
titleColor(tooltipItem) {
const titleLabelColor = tooltipItem.tooltip.labelColors[0].backgroundColor;
return titleLabelColor;
},
bodyColor() {},
},
datalabels: {
color: '#666666',
align: 'top',
anchor: 'end',
offset: 1,
formatter(value, context) {
const sumValue = context.chart.config.data.datasets.map((datapoint) => datapoint.data[context.dataIndex]);
function totalSum(total, datapoint) {
return total + datapoint;
}
const sum = sumValue.reduce(totalSum, 0);
return `${sum}`;
},
font: {
weight: 'bold',
size: 16,
},
},
},
scales: {
x: {
ticks: {
color: 'black',
font: {
weight: 'bold',
size: 16,
},
},
stacked: true,
},
y: {
ticks: {
stepSize: 1,
font: {
size: 18,
},
},
stacked: true,
},
},
layout: {
padding: 20,
},
},
};
/* eslint-disable no-new */
new Chart(ctx, BarChart);
},
};
and this is the BarAllYearData:
const DonutAllYearData = {
labels: [
'Butuh Perhatian Khusus',
'Dalam Proses',
'Selesai',
],
datasets: [{
label: 'My First Dataset',
data: [16, 3, 5],
backgroundColor: [
'#FF7A00',
'#23C4DB',
'#666666',
],
hoverOffset: 4,
}],
};
export default DonutAllYearData;
I'm using vue 3 by the way.
Anyway, thanks for the help

how to only show zero grid axes at center and hide all other gridlines in chart js

I am trying to hide all the grid lines on y axis except the middle line which shows the positive values above x axis and negative below y axis.
I found out that zeroWidthLine option isnt avaiable in version 3 anymore.I am attching the js fiddle link in comment.
You can use scriptable options for the grid color to achieve this:
Chart.register(ChartDataLabels);
chartLabels = ['2018', '2019', '2020', 'TTM']
equityToAssetData = [4.32, -5.37, 4.73, 4.89, 3.6, ];
var equityToAssetDatasets = {
labels: chartLabels,
datasets: [{
type: 'line',
label: 'Equity to Asset ',
data: equityToAssetData,
backgroundColor: 'rgb(97,207,5)',
borderColor: 'rgb(97,207,5)',
borderWidth: 1.8,
lineTension: 0.4,
pointStyle: 'rectRot'
}]
}
var chartStylingSingle = {
animation: {
duration: 500,
},
responsive: true,
layout: {
padding: 20
},
interaction: {
mode: 'index',
intersect: false
},
elements: {
point: {
hoverRadius: 5
}
},
plugins: {
legend: {
display: false,
},
datalabels: {
borderWidth: 0.5,
color: 'green',
anchor: 'start',
align: 'end',
offset: 6,
formatter: (v, ctx) => {
let label = ctx.chart.data.labels[ctx.dataIndex];
if (label != 'TTM') {
label = ' ' + label;
}
return label + '\n ' + v;
},
font: {
size: 11,
weight: 'bold',
}
}
},
scales: {
y: {
display: true,
grid: {
color: (ctx) => (ctx.tick.value === 0 ? 'rgba(0, 0, 0, 0.1)' : 'transparent')
}
},
x: {
display: true,
grid: {
display: false,
}
}
}
}
var ctx = document.getElementById('equityToAsset').getContext('2d');
var myChart = new Chart(ctx, {
data: equityToAssetDatasets,
options: chartStylingSingle
})
<canvas id="equityToAsset"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>

Chart js padding isn't working for data labels

I tried adding padding above my graphs, but it did not work. I went to the options.layout.padding section of the graph. The data labels just sit on top of the bar and look really bad. So either a way to add padding above graph, or some way to fix the labels being on top of the bars would help. I am using the Chart js data labels plugin.
Javascript Code:
<div class="row">
<div class="col-md-6 col-sm-12 col-xs-12">
<canvas id="myChart" class="bar-chart"></canvas>
<script>
Chart.register(ChartDataLabels); /* Register chart for data label plugin */
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Lithium Battery', 'Other Mfg', 'Delivery', 'Tailpipe', 'Fuel Cycle', 'Disposal', 'Total'],
value_labels: [ /* labels above the chart */
{{data['icev_lit_bat']}},
... (Ommited for space)
],
datasets: [{
label: 'ICEV CAR (MTCO2e/Year)',
data: [ /* errors are normal, fixes when server runs the code*/
[0, {{data['y1_icev']}}],
[{{data['y1_icev']}}, ... ommited for space
],
backgroundColor: [
'rgba(0,0,0,0.3)'
],
borderColor: [
'rgba(0,0,0,1)'
],
borderWidth: 1,
borderSkipped: false
}]
},
options: { /* Chart settings */
scales: {
y:{
ticks:{
font:{
size: 20
},
stepSize:0.5
},
max: 7,
min: 0,
stepSize: 1
},
x:{
ticks:{
font:{
size: 18
},
},
}
},
layout: {
padding: {
left: 0,
right: 0,
top: 30,
bottom: 0
}
},
responsive: false,
maintainAspectRatio: false,
plugins: {
legend: {
labels: {
font: {
size: 20
}
}
},
datalabels: {
color: '#000',
anchor: 'end',
formatter: function(value, context) { /* sets custom labels */
return context.chart.data.value_labels[context.dataIndex];
}
}
},
y: {
beginAtZero: true
}
}
});
</script>
</div>
I figured it out. You need to use align: 'top'
plugins: {
legend: {
labels: {
font: {
size: 20
}
}
},
datalabels: {
color: '#000',
anchor: 'end',
align: 'top',
formatter: function(value, context) { /* sets custom labels */
return context.chart.data.value_labels[context.dataIndex];
}
}
},

How to prevent an ApexCharts chart label from being slanted

I am working on my project with Django where I need to use Javascript and a chart library. I have two charts that I made with ApexCharts, but I don't know how to prevent the label text to being slant and overflow. I can't find anything about this problem in the documentation or I'm not enough familiar to find what I need. :)
var options07 = {
series: [{
name: 'SOHA',
data: [ {{i.szervkult07a}} ]
}, {
name: 'RITKÁN',
data: [ {{i.szervkult07b}} ]
}, {
name: 'IDŐNKÉNT',
data: [ {{i.szervkult07c}} ]
}, {
name: 'GYAKRAN',
data: [ {{i.szervkult07d}} ]
}, {
name: 'MINDIG',
data: [ {{i.szervkult07e}} ]
}],
chart: {
type: 'bar',
height: 350,
stacked: true,
stackType: '100%'
},
responsive: [{
breakpoint: 480,
options: {
legend: {
position: 'bottom',
offsetX: -10,
offsetY: 0
}
}
}],
xaxis: {
categories: ['A cég gondot fordít az ügyfelek igényeinek minél jobb megismerésére'
],
},
fill: {
opacity: 1
},
legend: {
position: 'right',
offsetX: 0,
offsetY: 50
},
};
var chart = new ApexCharts(document.querySelector("#chart_szk07"), options07);
chart.render();
var options07b = {
series: [{
name: 'SOHA',
data: [{{i.szervkult07a}}]
}, {
name: 'RITKÁN',
data: [{{i.szervkult07b}}]
}, {
name: 'IDŐNKÉNT',
data: [{{i.szervkult07c}}]
}, {
name: 'GYAKRAN',
data: [{{i.szervkult07d}}]
}, {
name: 'MINDIG',
data: [{{i.szervkult07e}}]
}],
chart: {
type: 'bar',
height: 350
},
plotOptions: {
bar: {
horizontal: false,
columnWidth: '55%',
endingShape: 'rounded'
},
},
dataLabels: {
enabled: false
},
stroke: {
show: true,
width: 2,
colors: ['transparent']
},
xaxis: {
categories: ['A cég gondot fordít az ügyfelek igényeinek minél jobb megismerésére'],
},
yaxis: {
title: {
text: 'fő'
}
},
fill: {
opacity: 1
},
tooltip: {
y: {
formatter: function (val) {
return val + " fő"
}
}
}
};
var chart = new ApexCharts(document.querySelector("#chart_szk07b"), options07b);
chart.render();
From the docs, You should be able to add rotate: 0 to the labels section of xaxis. I suggest trying to shorten those. I imagine a long label will not look as good as a shorter one.
xaxis: {
categories: ['A cég gondot fordít az ügyfelek igényeinek minél jobb megismerésére'],
labels: {
rotate: 0
}
}

Echart icon in series tooltip

So i have the following configuration:
const frequencyChartoption = {
title: {},
tooltip: {},
legend: {
data: ['Frekvens', 'Vigtighed']
},
xAxis: {
type: 'category',
data: ['marker_01', 'marker_02'],
axisLabel: {
formatter: function (value) {
return '{' + value + '| }\n{value|}';
},
margin: 20,
rich: {
value: {
lineHeight: 30,
align: 'center'
},
marker_01: {
height: 20,
align: 'center',
backgroundColor: {
image: icons.marker_01
}
},
marker_02: {
height: 20,
align: 'center',
backgroundColor: {
image: icons.maker_02
}
},
}
}
},
yAxis: {},
series: [{
name: 'Frekvens',
type: 'bar',
data: frequencyChartFrequencyScore,
tooltip: icons.marker_01,
itemStyle: {
normal: {
color: colors[0],
label: {
interval: 5,
show: true,
position: 'top',
formatter: '\n{c}'
}
}
}
},
{
name: 'Vigtighed',
type: 'bar',
data: frequencyChartImportance,
itemStyle: {
normal: {
color: colors[1],
label: {
show: true,
position: 'top',
formatter: '\n{c}'
}
}
}
}
]
};
Now as you can see i am using two images as my xAxis
Now i wish to make these show up on my tooltip when i hover over the chart. However i am not quite sure how to do that and was hoping some of you might be able to help?
Simply stated, a series may have a tooltip but the tooltip must be listed as an object with an identifying trigger (see tooltip documentation).
series: [{
name: 'Frekvens',
type: 'bar',
data: frequencyChartFrequencyScore,
tooltip: {
show: true,
trigger: 'axis',
formatter: (params) => {
// see tooltip.formatter for details
// you want to focus on the 'marker' property
return params[0].name;
}
}
}]
With this in mind, you can set two variables and print them as need be within the output of your tooltip. See the additional example below (from CodePen).
var myChart = echarts.init(document.getElementById("main"));
// specify chart configuration item and data
var option = {
title: {
text: "ECharts entry example"
},
tooltip: {
show: true,
trigger: "axis",
backgroundColor: 'rgba(0, 0, 0, 0.8)',
formatter: (params) => {
// create new marker
var icon0 = `<span data-tooltip="minimum" style="border-left: 2px solid #fff;display: inline-block;height: 12px;margin-right: 5px;width: 20px;"><span style="background-color:${params[0].color};display: block;height: 4px;margin-top: 4px;width: 20px;"></span></span>`;
var icon1 = `<span data-tooltip="implied-high" style="background-color:rgba(255,255,255,.75);border-radius: 2px;display: inline-block;height: 12px;margin-right:5px;width: 20px;"><span style="background-color:${params[0].color};border: 1px solid ${params[0].color};border-radius:50%;display:block;height:6px;margin-left:7px;margin-top:3px;width:6px;"></span></span>`;
console.log("params", params, params[0].name);
return `${icon0} ${params[0].name}
${icon1} ${params[0].value}`;
},
textStyle: {
fontWeight: 'bold',
fontSize: 18
}
},
legend: {
data: ["Sales"]
},
xAxis: {
data: ["shirt", "cardign", "chiffon shirt", "pants", "heels", "socks"]
},
yAxis: {},
series: [
{
name: "Sales",
type: "bar",
data: [5, 20, 36, 10, 10, 20]
}
]
};
// use configuration item and data specified to show chart
myChart.setOption(option);

Categories

Resources