Letter Spacing and line height of Data labels in Chart JS - javascript

I am working with chart.js to show some bar charts in reports. I was able to successfully integrate it in to my rails application and the bar charts are working fine.
For displaying data labels, I have used this plugin which also seems to work fine.
The problem I am facing now is the label styling. I am successfully able to change the color and font of the labels but unable to modify the letter spacing. I feel the labels are looking a bit cramped and vertically elongated and letter spacing would make it look better. I have attached the chartJS code and screenshot below.
Chart.defaults.global.plugins.datalabels.anchor = 'end';
Chart.defaults.global.plugins.datalabels.align = 'end';
Chart.defaults.global.legend.display = false;
// Chart.defaults.global.tooltipenabled = false;
$('.bar-chart-basic').each(function (i,obj)
{
var ctx = this.getContext('2d');
var gradient = ctx.createLinearGradient(0, 0, 0, 100);
gradient.addColorStop(1, '#76ddfb');
gradient.addColorStop(0, '#2471a2');
var x_values = JSON.parse(obj.dataset.x_axis)
var y_values = JSON.parse(obj.dataset.y_axis)
var data = {
labels: x_values,
datasets: [{
data: y_values,
backgroundColor: gradient,
display: false,
scaleLabel: ""
}]
}
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
responsive:true,
maintainAspectRatio: false,
datalabels: {
display:false
},
legend:{
display: false,
labels: {
fontSize: 0
}
},
options: {
hover: { mode: null,animationDuration:0 },
tooltips: {enabled: false },
layout: {
padding: {
left: 0,
right: 0,
top: 18,
bottom: 0
}
},
plugins: {
datalabels:
{
align: function()
{
return 'end';
},
anchor: 'end',
color: function() {
return 'slategrey';
},
font: {
size: 8.5
},
opacity: 1,
formatter: function(value, context) {
div_id = context.chart.canvas.id;
var y_labels = JSON.parse(context.chart.canvas.dataset.labels)
display_text = y_labels[context.dataIndex]
return display_text
}
}
},
scales: {
yAxes: [{
display: false,
gridLines: {
display:false,
color: '#6c757d'
},
ticks: {
// max: Math.max.apply(Math,data.datasets[0].data.map(function(x) {return Math.abs(x)}))*2.5,
beginAtZero: true
}
}],
xAxes: [{
barPercentage: 1.0,
barThickness:20,
gridLines: {
display: false,
drawBorder: false
},
ticks: {
fontSize: 8 ,
fontStyle: "bold",
fontColor: "slategrey"
}
}]
}
}
});
});
Happy to give more clarity.
UPDATE
With the help of the comment by Joel Hager was able to add line spacing by editing the canvas css. But still unable to update line height of the label

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

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 display final point value in charts.js

I'm using Charts.js library to display a line graph from data which is constantly updated. Is there a way to display only the final point value at all times? I want it to do this to monitor the added values at all times.
javascript code:
var config2 = {
type: 'line',
data: {
labels: 0,
datasets: [{
label: "No selection",
lineTension: 0,
borderColor: "rgba(222, 44, 31)",
pointBackgroundColor: "#fff675",
fill: false,
data: 0,
}
]
},
options: {
responsive: true,
title: {
display: false,
text: 'Chart.js Time Point Data'
},
scales: {
x: {
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
ticks: {
major: {
enabled: true
},
fontStyle: function(context) {
return context.tick && context.tick.major ? 'bold' : undefined;
},
fontColor: function(context) {
return context.tick && context.tick.major ? '#FF0000' : undefined;
}
}
},
y: {
display: true,
scaleLabel: {
display: true,
labelString: 'value'
}
}
}
}
};
Each time, a new value is available, you can simply remove outdated labels and dataset.data values once a certain limit is reached. This can be done using Array.shift(), which removes the first element from an array. Once these array are updated, you need to invoke chart.update().
var maxValues = 4;
setInterval(() => {
chart.data.labels.push(new Date());
chart.data.datasets[0].data.push(Math.floor((Math.random() * 20) + 1));
if (chart.data.labels.length > maxValues) {
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
}
chart.update();
}, 1000);
For displaying the value on the last added data point, you can use the Plugin Core API. It offers different hooks that may be used for executing custom code. In below runnable code snippet, I use the afterDraw hook to draw text directly on the canvas.
var chart = new Chart('chart', {
type: "line",
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
var iLastValue = chart.data.labels.length - 1;
var lastValue = chart.data.datasets[0].data[iLastValue];
var x = xAxis.getPixelForValue(chart.data.labels[iLastValue]);
var y = yAxis.getPixelForValue(lastValue);
ctx.save();
ctx.textAlign = 'center';
ctx.font = '14px Arial';
ctx.fillStyle = "red";
ctx.fillText('Value: ' + lastValue, x, y - 15);
ctx.restore();
}
}],
responsive: true,
maintainAspectRatio: false,
data: {
labels: [],
datasets: [{
label: "Data",
data: [],
fill: false,
lineTension: 0,
backgroundColor: "white",
borderColor: "red",
}]
},
options: {
layout: {
padding: {
right: 50
}
},
scales: {
xAxes: [{
type: 'time',
ticks: {
source: 'auto'
},
time: {
unit: 'second',
displayFormats: {
second: 'mm:ss'
},
tooltipFormat: 'mm:ss'
},
}],
yAxes: [{
ticks: {
min: 0,
max: 20,
stepSize: 5
}
}]
}
}
});
var maxValues = 4;
setInterval(() => {
chart.data.labels.push(new Date());
chart.data.datasets[0].data.push(Math.floor((Math.random() * 20) + 1));
if (chart.data.labels.length > maxValues) {
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
}
chart.update();
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="chart" height="90"></canvas>

Multi-axis line chart with Chart.js

The following code I tried to display two y-axis on the line chart and I added yAxisID in both the data source. However, it is nothing to shown. May I know what's wrong with my code? Thank you.
function BuildChart(labels, valuesa, valuesb, chartTitle) {
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Temperature',
fill: false,
data: valuesa,
yAxisID: 'y1',
backgroundColor: 'red',
borderColor: 'red',
}, {
label: 'Relative Humidity',
fill: false,
data: valuesb,
yAxisID: 'y2',
backgroundColor: 'blue',
borderColor: 'blue',
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y1: {
type: 'linear',
display: true,
position: 'left',
},
y2: {
type: 'linear',
display: true,
position: 'right',
},
xAxes: [{
ticks: {
beginAtZero: true,
scaleLabel: {
display: false,
labelString: ''
}
}
}],
yAxes: [{
scaleLabel: {
display: false,
labelString: '',
}
}]
}
}
})
return myChart;
};
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.response);
// Map json labels back to values array
var labels = json.feed.entry.map(function(e) {
return e.gsx$tag.$t;
});
// Map json values back to values array
var valuesa = json.feed.entry.map(function(e) {
return e.gsx$dailytemperature.$t
});
// Map json values back to values array
var valuesb = json.feed.entry.map(function(e) {
return e.gsx$dailyrh.$t
});
BuildChart(labels, valuesa, valuesb, "Temperature", "Relative Humidity");
}
};
xhttp.open("GET", "https://spreadsheets.google.com/", false);
xhttp.send();
Within the chart options of your code, there are too many definitions of yAxes (before and after xAxis).
To make it work, the entire chart options can basically be reduced to what you see below.
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
type: 'linear',
position: 'left',
id: 'y1',
},
{
type: 'linear',
position: 'right',
gridLines: {
drawOnChartArea: false
},
id: 'y2',
}
]
}
}
For further information, please consult Create Multiple Axis from the
Chart.js documentation.

How to show border around tooltip chart.js and show y-axis integer value along with text in tooltip title?

i am drawing a line chart using chart.js and showed a tooltip on graph.But i am not able to draw a border around tooltip and in title i want to show text and current y-axis value as title(eg.total count:2 but instead of 2 it showing undefined.Now i removed code from title callback). I am trying for many days but still no luck. Please help me. Here is my code
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels:["a","b","c"],
datasets: [{
label: 'Total count',
lineTension: 0,
data: [2,4,6],
fill: false,
borderColor: 'rgba(39,50,139,1)',
pointBackgroundColor:'rgba(176,179,214,1)',
pointBorderColor:'rgba(39,50,139,1)',
pointRadius:5,
pointHoverBackgroundColor:'rgba(39,50,139,1)',
borderWidth:2
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
legend:{
display:false
},
chartArea: {
backgroundColor: '#fff'
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
maxTicksLimit:3
}
}],
xAxes: [{
gridLines: {
display: false,
color: "black"
},
ticks: {
max:12,
maxTicksLimit:12
}
}]
},
tooltips: {
callbacks: {
title:function(tooltipItem, data) {
},
afterLabel: function(tooltipItem, data) {
return userNamesResult[tooltipItem.index];
}
},
titleSpacing:0,
titleMarginBottom:0,
titleFontColor:'#000',
backgroundColor: '#f2f3f4',
bodyFontColor: '#000',
//bodyFontStyle:'bold',
bodyFontSize: 14,
displayColors: false,
borderColor:'#ff0000',
borderWidth:5,
}
}
});

Categories

Resources