I am using Chart JS to plot data and on the date axis (x-axis) shows '20 Dec 2018', how can I translate the months string to a different language? I was hoping it would be set to whatever language is set on the browser, but nope.
The tooltip, when hovering a data point, needs translation too.
I manage to solve this by creating callback functions on xAxis : ticks
and tooltips : title
when creating the chart.
Here is my code that sets up the chart.js:
<script>
var data = JSON.parse('<?php echo $data?>');
var ctx = document.getElementById("points-given-chart").getContext('2d');
var chartPoints = new Chart( ctx, {
type: 'line',
data: {
datasets: [
{
data: data,
borderWidth: 3,
label: 'Pontos',
borderColor: 'rgba(246, 185, 59,1.0)',
backgroundColor: 'rgba(250, 211, 144,1.0)',
}
]
},
options: {
responsive: true,
title: {
display: false,
text: "Pontos"
},
scales: {
xAxes: [{
type: "time",
time: {
unit: 'day',
tooltipFormat: 'D MMM, YYYY',
displayFormats: {
day: 'D MMM'
},
distribution: 'series'
},
scaleLabel: {
display: true,
},
ticks : {
// Here's where the magic happens:
callback: function( label, index, labels ) {
return translate_this_label( label );
}
}
}],
yAxes: [{
scaleLabel: {
display: false,
labelString: 'Pontos'
},
ticks : {
beginAtZero : true,
callback: function( label, index, labels ) {
if ( label > 1 )
return formatNumber( label, 0, ',', '.');
else
return label;
}
}
}]
},
elements: {
line: {
tension: 0.2, // disables bezier curves
}
},
legend: {
display: false
},
tooltips: {
callbacks: {
// Here's where the magic happens:
title: function( data ) {
return translate_this_label( data[0].xLabel );
},
label: function ( item, data ) {
return 'Pontos: ' + formatNumber( item.yLabel, 0, ',', '.');
}
}
}
}
});
</script>
And here are the helper functions to perform the translations:
function translate_month( month ) {
var result = month;
switch(month) {
case 'Feb':
result = 'Fev' ;
break;
case 'Apr':
result = 'Abr' ;
break;
case 'May':
result = 'Mai' ;
break;
case 'Aug':
result = 'Ago' ;
break;
case 'Sep':
result = 'Set' ;
break;
case 'Dec':
result = 'Dez' ;
break;
}
return result;
}
function translate_this_label( label ) {
month = label.match(/Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Nov|Dec/g);
if ( ! month )
return label;
translation = translate_month( month[0] );
return label.replace( month, translation, 'g' );
}
Import moment-with-locales.min.js
Set your language before chart load:
moment.locale('pt-BR');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With