Syntax for chartjs datalabels plugin - javascript

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%"
// ...

Related

chart js 3.9.1 - barchart - margin left

how do i reduce the space between the bar and the y scale? I tried with padding but it doesn't work
Thanks
This is my configuration,I upload the data at runtime and update the graph
Chart.register(ChartDataLabels);
var options = {
tooltips: {
enabled: false
},
plugins:
{
datalabels:
{
color: 'white'
},
legend: {
position: 'top', labels:
{
font: {size: 10},
usePointStyle: true
}
}
},
scales:
{
x: {
barPercentage: 6.5,
categoryPercentage: 0.1
},
y: {
barPercentage: 1,
categoryPercentage: 1,
beginAtZero: true,
grace: '3%',
ticks: {
beginAtZero: true
}
}
}
};
var barChart = new Chart(document.getElementById("chart3"), {
type: 'bar',
data:
{
labels: [""]
},
options:options
});
for (i = 0; i < parsed[0].length; i++)
{
barChart.data.datasets.push({ label: parsed[0][i].label, backgroundColor: parsed[0][i].backgroundColor, data: ["" + parsed[0][i].data + ""], pointStyle:'circle' });
}
barChart.update();
The issue sounds being related to categoryPercentage and barPercentage options that you are set in the axis but this is not the right place.
Move those options in the chart.options and it should work.
Try using categoryPercentage: 1.
var options = {
categoryPercentage: 1,
plugins:
{
datalabels:
{
color: 'white'
},
legend: {
position: 'top', labels:
{
font: {size: 10},
usePointStyle: true
}
}
tooltip: {
enabled: false
},
},
scales:
{
y: {
beginAtZero: true,
grace: '3%',
}
}
};

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

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 add a vertical line on the end of the chart.js scatter graph

This is how options for my chart look like
options: {
legend: {
display: false
},
scales: {
xAxes: [
{
type: "time",
gridLines: {
display: false
},
ticks: {
padding: 15
}
}
],
yAxes: [
{
ticks: {
padding: 22,
min: 1,
max: 5,
stepSize: 1
},
position: "left",
gridLines: {
drawTicks: false
}
}
]
}
}
as you can see there is an option
gridLines: {
display: false
},
because of this there is no vertical lines on the chart.
What I want to do is to add only one vertical line on the end of the chart(right side of the chart)
Here is my live example https://codesandbox.io/s/line-chart-with-vanilla-js-and-chartjs-pi9fn?file=/src/index.js
This can be solved as follows:
Define data.labels in the chart configuration. Given your data, this could be done by extracting the x values of of the data objects using Array.map().
const labels = data.map(o => o.x);
Then you need to adapt xAxis.ticks in order to instruct Chart.js that ticks (including grid lines) have to be generated from user given labels (see Tick Source from Chart.js documentation).
ticks: {
source: 'labels'
}
Further you have to change the definition of xAxis.gridLines. Make them displayed again and define lineWidth instead. This should be an array of numbers that specify the stroke width of individual grid lines. Basically all 0 except 1 for the last number.
gridLines: {
lineWidth: labels.map((l, i) => i < labels.length - 1 ? 0 : 1)
}
Please have a look at the runnable code snippet below.
const data = [
{ x: "1-01", y: 1 },
{ x: "1-07", y: 3 },
{ x: "1-14", y: 2 },
{ x: "1-21", y: 4 },
{ x: "1-28", y: 5 },
{ x: "2-04", y: 1 }
];
const labels = data.map(o => o.x);
new Chart('line-chart', {
type: "scatter",
responsive: true,
maintainAspectRatio: false,
data: {
labels: labels,
datasets: [
{
data: data,
label: "A",
showLine: true,
fill: false,
borderWidth: 4,
pointRadius: 5,
tension: 0,
backgroundColor: "#ffffff",
borderColor: "red"
}
]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [
{
type: 'time',
unit: 'day',
time: {
parser: 'M-D'
},
gridLines: {
lineWidth: labels.map((l, i) => i < labels.length - 1 ? 0 : 1)
},
ticks: {
source: 'labels',
padding: 15
}
}
],
yAxes: [
{
ticks: {
padding: 22,
min: 1,
max: 5,
stepSize: 1
},
position: "left",
gridLines: {
drawTicks: false
}
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="line-chart" height="90"></canvas>

Categories

Resources