In chart.js, Is it possible to hide x-axis label/text of bar chart if accessing from mobile ?
Charts.js provides the responsive charts configuration options among
which there is the onResize
method. It gets passed two arguments: the chart instance and the new size. Should you log both to the console you'll see the complete chart instance there that includes all the regular options to control the chart instance scales
.
I added this to the options
object on the Bar
chart instance so the X axis disappears on resize to the width of 768 px then appears on the resize back to the desktop screen size. The Bar
instance was the Chart.js React wrapper provided by the react-chartjs-2 library.
<Bar
data={barData}
options={{
// default value
responsive: true,
onResize: function(newChart, newSize) {
console.log('newChart:', newChart);
console.log('newSize:', newSize);
if (newSize.width < 768) {
newChart.options.scales.xAxes[0].display = false;
} else {
newChart.options.scales.xAxes[0].display = true;
}
}, ...
For a Pie
instance switch newChart.options.scales.xAxes[0].display
for newChart.options.legend.display
.
They added the option, 2.1.4 (and maybe a little earlier) has it
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
ticks: {
display: false
}
}]
}
}
}
You can extend the current BarChart and remove the xLabels like this.
function registerCustomBarChart() {
Chart.types.Bar.extend({
name: "customBarChart",
initialize: function (data) {
Chart.types.Bar.prototype.initialize.apply(this, arguments);
var xLabels = this.scale.xLabels
xLabels.forEach(function (label, i) {
xLabels[i] = '';
})
}
});
}
var myBarChart = new Chart(context).customBarChart(data);
I've added a new option.
http://www.knighttube.com/scripts/chart.js
http://www.knighttube.com/scripts/chart.min.js
showXAxisLabel:false
I got around this by defining labels as a list of empty strings. Example:
var data = {
labels: ["", "", "", "", ""],
datasets: [{
label: "TEST",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [10, 20, 15, 8, 22]
}]
};
For this you need the label to not be relevant in the tooltip box. I defined mine as follows:
tooltipTemplate: "Latency: <%=value%>"
The simplest solution is:
scaleFontSize: 0
see the chart.js Document