I have the following HTML/JS code as follows which takes two lists:
- labels
- values
And converts it into a line chart with labels on the points:
<div style = "position:relative; bottom:140px; z-index: -2;">
<canvas id="lineChart" width = 600 height = 200></canvas>
<script>
Chart.register(ChartDataLabels);
var ctx = document.getElementById("lineChart").getContext("2d");
var linechart = new Chart(ctx, {
type: "line",
data: {
labels: {{ labels | safe}},
datasets: [
{
label: "Data points",
data: {{ values | safe}},
fill: false,
borderColor: "rgb(75, 192, 192)",
lineTension: 0.5
}
]
},
options: {
responsive: true,
layout: {
padding: {
top: 100
}
},
scales: {
x: {
grid: {
display: false
}
},
y: {
display: false,
}
},
plugins: {
legend: {
display: false
},
datalabels: {
anchor: 'end',
align: 'top',
formatter: Math.round,
font: {
weight: 'bold',
size: 15
}
}
}
}
});
</script>
This is working fine:
However, I want the labels to have the '£'
symbol before and 'm'
after
Every time I try to use the formatter function like:
formatter: function(value){
return value 'm';
Or any other combination, the chart fails to return. I am completely perplexed why.
Any suggestions?
CodePudding user response:
The following formatter
works fine for me.
formatter: v => '£' v 'm'
Please take a look at your amended and runnable code below.
Chart.register(ChartDataLabels);
new Chart('myChart', {
type: "line",
data: {
labels: [2015, 2016, 2017, 2018, 2019, 2020, 2021],
datasets: [{
label: "Data points",
data: [567, 894, 883, 833, 710, 714, 578],
fill: false,
borderColor: "rgb(75, 192, 192)",
lineTension: 0.5
}]
},
options: {
responsive: true,
layout: {
padding: {
top: 100
}
},
scales: {
x: {
grid: {
display: false
}
},
y: {
display: false,
}
},
plugins: {
legend: {
display: false
},
datalabels: {
anchor: 'end',
align: 'top',
formatter: v => '£' v 'm',
font: {
weight: 'bold',
size: 15
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>
<canvas id="myChart" height="100"></canvas>
If your code still doesn't work, there may be a syntax error somewhere. Try to open your browser's
DevTools
and check the console tab for any errors that help you locate the source of the problem.