Chart js padding isn't working for data labels - javascript

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];
}
}
},

Related

Chart js how to move legend to bottom but save legend type as list

Hi!. How could I do as in example image which i pinned? I want to make donut in center and two legends column under the chart.
Here is my code which i write - but it make very ugly legends by default. I want save this legend style but move them to bottom.
I watched many youtube video how to do it but i dont understand how.
var token_allocations_ctx = d("token_allocations_canvas");
var token_allocations_chart = new Chart(token_allocations_ctx, {
type: 'doughnut',
data: {
labels: token_allocations_labels,
datasets: [{
label: 'Allocations',
data: token_allocations_data,
backgroundColor: [
'#8b03f7'
],
borderWidth: 0,
hoverBorderWidth: 0,
borderAlign: 'center',
hoverOffset: 15,
}]
},
options: {
animation: {
animateScale: false
},
cutout: "80%",
borderRadius: 30,
responsive: true,
radius: 100,
layout: {
padding: 18
},
plugins: {
legend: {
position: "right",
align: "right",
labels: {
usePointStyle: true,
boxWidth: 100
}
},
tooltip: {
// displayColors: false,
usePointStyle: true,
boxWidth: 10,
callbacks: {
label: function(context) {
let label = context.dataset.label || '';
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
console.log(context)
label += token_allocations_labels_procent[context.dataIndex]
}
return label;
},
title: function(context) {
return context.label;
},
}
},
},
}
});

Syntax for chartjs datalabels plugin

Could not find a simple example for this:
Trying to create a curved line in Chart.js and add fairly simple labels.
Got close but need some help as my JS is not my forte and the documentation is a bit confusing.
So, I have 1 line with 4 dots (x,y) and a second dataset with 1 dot:
<!DOCTYPE html>
<html>
<body>
<div>
<canvas id="linechart" width="500" height="500" style="display: block; box-sizing: border-box; height: 400px; width: 400px;"/>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.0.0/dist/chart.min.js"/>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0"/>
<script>
var linedata = {
datasets: [
{
data: [{x:70,y:50}]},
{
datasets: [{
// Change options only for labels of THIS DATASET
datalabels: {
color: 'yellow'
}
}],
data: [{
x: 0,
y: 90
}, {
x: 69,
y: 78
}, {
x: 150,
y: 55
}, {
x: 165,
y: 0
}
],
showLine: true,
fill: false,
lineTension: 0.4,
bezierCurve: true,
borderColor: 'rgba(10, 200, 40, 1)'
}
]
};
var chartOptions = {
plugins: {
datalabels: {
color: 'blue',
labels: {
title: {
font: {
weight: 'bold'
}
},
value: {
color: 'green'
}
}
}
},
animation: {
duration: 0
},
responsive: false,
maintainAspectRatio: true,
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
type: 'linear',
position: 'bottom',
ticks: {
stepSize: 10,
max: 180
}
}],
yAxes: [{
ticks: {
stepSize: 10,
max: 100
}
}]
}
};
var lineID = document.getElementById('linechart').getContext('2d');
var lineChart = new Chart(lineID, {
type: 'scatter',
data: linedata,
options: chartOptions,
plugins:[ChartDataLabels]
});
</script>
</body>
</html>
What I need is the syntax to define each dot as 'predefined text'+value/
for example the second dot should say 'pressure: 65'.
I believe the answer is here:
https://chartjs-plugin-datalabels.netlify.app/guide/formatting.html#data-transformation
But my JS isn't good enough....
surly this will help
try using formatter function in datalabels
https://chartjs-plugin-datalabels.netlify.app/guide/formatting.html#custom-labels
below return statement will give you the label defined for the point, alter ot as you like
datalabels: {
formatter: function(value, context) {
return context.chart.data.labels[context.dataIndex];
}
}
this example below is the syntax you need
formatter: function(value, context) {
return context.dataIndex + ': ' + Math.round(value*100) + '%';
}
// label for data at index 0 with value 0.23: "0: 23%"
// label for data at index 1 with value 0.42: "1: 42%"
// ...

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

Displaying labels on a Doughnut Chart using Chart.js

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>

How to set percentage value by default on each bars in horizontal bar chart js

I have used horizontal bar chart from chart.js where i need percentage values to be shown next to each bar at right side? here is the bar sample image.
click here to view sample image of bar chart
Also these are the options i have tried :
xAxes: [
{
ticks: {
min: 0,
max: 100
},
grid: {
offset: false
}
},
],
yAxes: [
{
gridLines: {
display: false,
},
display: "right",
barPercentage: 0.8,
minBarLength: 2,
},
],
Is there any option which can turn the percentage values on at he right side of the horizontal bar chart?
Please click below image to see the expected output
click image expected output
You can make use of the datalabels plugin
Example:
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.3.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0-rc"></script>
<canvas id="myChart" width="850" height="520"></canvas>
<script>
var ctx = document.getElementById('myChart');
Chart.register(ChartDataLabels);
Chart.defaults.set('plugins.datalabels', {
color: '#FE777B'
});
var myChart = new Chart(ctx, {
type: 'bar',
plugins: [ChartDataLabels],
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
data: [12, 19, 3, 5, 2, 3],
label: 'Advisor Closed MTD',
backgroundColor: 'rgb(192,111,94)',
barThickness: 25,
datalabels: {
color: '#FFCE56'
}
}],
},
options: {
indexAxis: 'y',
responsive: false,
plugins: {
datalabels: {
formatter: (val, context) => (`${val}%`),
anchor: 'end',
align: 'end',
labels: {
value: {
color: 'blue'
}
}
}
}
}
});
</script>

Categories

Resources