I'm developing a site that uses chart.js (www.chartjs.org).
I have to make a line chart that shows multiple series of data, that users can hide or show by clicking on the respective legend symbol (similar to this http://js.syncfusion.com/demos/web/#!/azure/chart/linechart).
Is there any way to do it with chartjs?
You can try this
Create store for hidden datasets
window.chartName = new Chart(...
window.chartName.store = new Array();
Then use this function to update chart, must be handled by click on legend item
function updateDataset(legendLi, chart, label) {
var store = chart.store;
var exists = false;
for (var i = 0; i < store.length; i++) {
if (store[i][0] === label) {
exists = true;
chart.datasets.push(store.splice(i, 1)[0][1]);
legendLi.fadeTo("slow", 1);
}
}
if (!exists) {
for (var i = 0; i < chart.datasets.length; i++) {
if (chart.datasets[i].label === label) {
chart.store.push([label, chart.datasets.splice(i, 1)[0]]);
legendLi.fadeTo("slow", 0.33);
}
}
}
chart.update();
}
Don't forget updated legend template in chart options
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li class=\"legend-item\" onclick=\"updateDataset($(this), window.chartName, '<%=datasets[i].label%>')\"><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
Shortly, i added this onclick handler for li component
<li class=\"legend-item\" onclick=\"updateDataset($(this), window.chartName , '<%=datasets[i].label%>')\"><
For example fiddle
This is now available in Charts.js
From the documentation http://www.chartjs.org/docs/#chart-configuration-legend-configuration
Legend Configuration
The legend configuration is passed into the options.legend namespace.
The global options for the chart legend is defined in
Chart.defaults.global.legend.
onClick function(event, legendItem) {} A callback that is called when a 'click' event is registered on top of a label item
onHover function(event, legendItem) {} A callback that is
called when a 'mousemove' event is registered on top of a label item
An update to #benallansmith answer, the link to the documentation is now :
https://www.chartjs.org/docs/latest/configuration/legend.html
My version of the example code, to have datasets 2 and 3 hidden while clicking on legend for dataset 1 (datasets 2 and 3 have their legends hidden with the filter function):
public static readonly myChart: Chart.ChartConfiguration = {
type: 'line',
data: {
datasets: [
{
label: 'A',
borderColor: 'red',
fill: false,
lineTension: 0
},
{
label: 'B',
borderColor: 'blue',
fill: false,
lineTension: 0,
pointRadius: 0
},
{
borderColor: 'blue',
borderDash: [5, 10],
borderWidth: 1,
fill: false,
lineTension: 0,
pointRadius: 0
},
{
borderColor: 'blue',
borderDash: [5, 10],
borderWidth: 1,
fill: false,
lineTension: 0,
pointRadius: 0
}
]
},
options: {
legend: {
labels: {
filter: function(legendItem, chartData) {
if (legendItem.datasetIndex > 1) {
return false;
}
return true;
}
},
onClick: function(e, legendItem) {
const index = legendItem.datasetIndex;
if (index === 1) {
const ci = this.chart;
[
ci.getDatasetMeta(1),
ci.getDatasetMeta(2),
ci.getDatasetMeta(3)
].forEach(function(meta) {
meta.hidden = meta.hidden === null ? !ci.data.datasets[1].hidden : null;
});
ci.update();
} else {
// Do the original logic
Chart.defaults.global.legend.onClick.call(this, e, legendItem);
}
}
},
responsive: false,
animation: {
duration: 0
},
}
...
};
my version is v2.8.0
I find a work way, try it.
add
legend : {
}
into option
var donutOptions = {
maintainAspectRatio : false,
responsive : true,
animation: {
animateScale: true,
animateRotate: true
},
tooltips: {
intersect: false,
callbacks: {
label: function (tooltipItem, data) {
...
}
},
},
plugins: {
datalabels: {
...
},
},
},
legend : {
}
};
and use this
donutChart.chart.getDatasetMeta(0).data[index].hidden = true;
donutChart.update();
I've found no way to do this. It's easy to put some onclick behaviour on the legend template, and you can easily change the series stroke and colors alpha channel to 0 so that the area and stroke disappear but I've found no way to do this on points.
I've decided to use google charts for this particular chart, and chart.js whenever I do not need that behavior, hoping that the good creators of chart.js will add it in the future.
onLegendClick: function (e) {
var series = e.target;
series.isVisible() ? series.hide() : series.show();
},
dxcharts have a function called onLegendClick, a few others are onSeriesClick and onPointClick. I hope this helps.
Related
I'm creating graphs with ChartJS, but they seem to inherit the default colors of some parent element. The graphs look like this:
I am dynamically creating the charts, depending on selections from the user. The ChartJS chart takes in an array of either primitives, or objects to use as the chart data. I'm using the following function to create the chart objects, and then using an array of these objects as the parameter for ChartJS:
function getChartDataObject(data){
var title = data['metadata']['title'];
var color = random_rgba();
console.log(`Color: ${color}`);
var dataObject = {
label: title,
data: data['scaled_interval'],
color: color,
fill: false,
lineTension: 0,
radius: 1,
}
return dataObject;
}
Then I create the master chart with this function:
function createIntervalChart(intervalDataObjects, datetimeInterval) {
const cnvs = document.createElement('canvas');
const ctx = $(cnvs);
var data = {
labels: datetimeInterval,
datasets: intervalDataObjects,
}
var options = {
responsive: true,
title: {
display: true,
position: "top",
text: "Projected Load Profiles",
fontSize: 18,
fontColor: "#111",
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#333",
fontSize: 16
}
},
elements: {
point: {
radius: 0
}
},
plugins: {
zoom: {
zoom: {
wheel: {
enabled: true
},
pinch: {
enabled: true
},
mode: 'xy',
}
},
title: {
text: "Estimated Load Profiles"
}
}
};
var chart = new Chart(ctx, {
type: "line",
data: data,
options: options
});
return cnvs;
}
When I check the console, I see distinct colors created by the random_rgb() function, but they all turn out grey.
Color: rgba(215,231,183,0.6)
Color: rgba(253,61,199,0.1)
Color: rgba(27,15,88,0.1)
Does anyone know how to create a ChartJS chart with custom colors? Or how to override inherited styling for these charts? Thank you
color is not a valid dataset property for a line chart. Use borderColor and optionally also backgroundColor (will be used for drawing the legend label box).
function getChartDataObject(data){
var title = data['metadata']['title'];
var color = random_rgba();
console.log(`Color: ${color}`);
var dataObject = {
label: title,
data: data['scaled_interval'],
borderColor: color, // <- to be changed
fill: false,
lineTension: 0,
radius: 1,
}
return dataObject;
}
For further information, please consult Dataset Properties from the Chart.js documentation.
I'm trying to create one real-time flot and my problem is that I can't get to see the flot grid through the filling of my data's lines..
If you have any idea to get my filling a bit transparent like the picture below, I'd like to apply it as well on my Fiddle!
What I'm trying to achieve is something like that:
Picture of what I try to get
Here is the Fiddle on what I'm working:
My flot on Fiddle
Code:
$(function () {
getRandomData = function(){
var rV = [];
for (var i = 0; i < 10; i++){
rV.push([i,Math.random() * 10]);
}
return rV;
}
getRandomDataa = function(){
var rV = [];
for (var i = 0; i < 10; i++){
rV.push([i,Math.random() * 10 + 5]);
}
return rV;
}
getSeriesObj = function() {
return [
{
data: getRandomDataa(),
lines: {
show: true,
fill: true,
lineWidth: 5,
fillColor: { colors: [ "#b38618", "#b38618" ] },
tickColor: "#FFFFFF",
tickLength: 5
}
}, {
data: getRandomData(),
lines: {
show: true,
lineWidth: 0,
fill: true,
fillColor: { colors: [ "#1A508B", "#1A508B" ] },
tickColor: "#FFFFFF",
tickLength: 5
}
}];
}
update = function(){
plot.setData(getSeriesObj());
plot.draw();
setTimeout(update, 1000);
}
var flotOptions = {
series: {
shadowSize: 0, // Drawing is faster without shadows
tickColor: "#FFFFFF"
},
yaxis: {
min: 0,
autoscaleMargin: 0,
position: "right",
transform: function (v) { return -v; }, /* Invert data on Y axis */
inverseTransform: function (v) { return -v; },
font: { color: "#FFFFFF" },
tickColor: "#FFFFFF"
},
grid: {
backgroundColor: { colors: [ "#EDC240", "#EDC240" ], opacity: 0.5 }, // "Ground" color (May be a color gradient)
show: true,
borderWidth: 1,
borderColor: "#FFFFFF",
verticalLines: true,
horizontalLines: true,
tickColor: "#FFFFFF"
}
};
var plot = $.plot("#placeholder", getSeriesObj(), flotOptions);
setTimeout(update, 1000);
});
Thanks a lot!
You can use the rgba() color specification with flot to specify the fill color and alpha level (transparency):
fillColor: { colors: [ "rgba(179, 134, 24, .2)", "rgba(179, 134, 24, .2)" ] },
An alpha value of 0 is fully transparent, while an alpha value of 1 is fully opaque.
I know exactly how to enable legend in Highcharts, but the problem is how to create legends based on the value of the points from the same series since every legend is used to symbolize a series(a collection of points).
There's is a picture(chart type: waterfall) I draw in excel below illustrating what I want, you can see clearly that orange color legend stands for gaining, while blue one stands for loss, but how do I achieve this in Highcharts?
I've searched a lot but ended with disappointment, please help.
One way to do this is with a dummy series.
Create an extra series, with the name and color that you want, with an empty data array:
series: [{
name: 'Actual Series',
data: [...data, with points colored as needed...]
}, {
grouping: false,
name: 'Dummy Series',
color: 'chosen color',
data: []
}]
You'll also want to set grouping to false, so that the dummy series does not take up extra blank space on the plot.
Fiddle:
http://jsfiddle.net/jlbriggs/vjd3p4s0/
(also, the same thing using the Waterfall demo: http://jsfiddle.net/jlbriggs/7vtbzh53/ )
Another way to do this would be to create your own legend, outside of the chart.
Either way, you will lose the functionality of clicking the legend to show/hide the series of for the orange columns. You would have to build a more complex function to edit the data on legendItemClick if you that ability is important to you.
Solution for edited question. You can map your data to two series and set stacking to 'normal'.
const data = [10, 20, -10, 20, 10, -10];
const dataPositive = data.map(v => v >= 0 ? v : 0);
const dataNegative = data.map(v => v < 0 ? v : 0);
const options = {
chart: {
type: 'column'
},
series: [{
color: 'blue',
data: dataPositive,
stacking: 'normal'
}, {
color: 'orange',
data: dataNegative,
stacking: 'normal'
}]
}
const chart = Highcharts.chart('container', options);
Live example:
https://jsfiddle.net/j2o5bdgs/
[EDIT]
Solution for waterfall chart:
const data = [10, 20, -30];
const colors = Highcharts.getOptions().colors;
const options = {
chart: {
type: 'waterfall'
},
series: [{
// Single series simulating 2 series
data: data.map(v => v < 0 ? {
y: v,
color: colors[0]
} : {
y: v,
color: colors[3]
}),
stacking: 'normal',
showInLegend: false
}, {
// Positive data serie
color: colors[3],
data: [10, 20, 0],
visible: false,
stacking: 'normal',
showInLegend: false
}, {
// Negative data serie
color: colors[0],
data: [0, 0, -30],
visible: false,
stacking: 'normal',
showInLegend: false
}, {
// Empty serie for legend item
name: 'Series 1',
color: colors[3],
stacking: 'normal',
events: {
legendItemClick: function(e) {
const series = this.chart.series;
const invisibleCount = document.querySelectorAll('.highcharts-legend-item-hidden').length;
if (this.visible) {
if (invisibleCount === 1) {
series[0].hide();
series[1].hide();
series[2].hide();
} else {
series[0].hide();
series[2].show();
}
} else if (invisibleCount === 2) {
series[0].hide();
series[1].show();
} else {
series[0].show();
series[2].hide();
}
}
}
}, {
// Empty serie for legend item
name: 'Series 2',
color: colors[0],
stacking: 'normal',
events: {
legendItemClick: function(e) {
const series = this.chart.series;
const invisibleCount = document.querySelectorAll('.highcharts-legend-item-hidden').length;
if (this.visible) {
if (invisibleCount === 1) {
// hide all
series[0].hide();
series[1].hide();
series[2].hide();
return;
}
series[0].hide();
series[1].show();
} else {
if (invisibleCount === 2) {
series[0].hide();
series[2].show();
return;
}
series[0].show();
series[1].hide();
}
}
}
}]
}
const chart = Highcharts.chart('container', options);
Live example:
https://jsfiddle.net/2uszoLop/
I've just started working with Chart.js, and I am getting very frustrated very quickly. I have my stacked bar chart working, but I can't get the click "events" to work.
I have found a comment on GitHub by nnnick from Chart.js stating to use the function getBarsAtEvent, even though this function cannot be found in the Chart.js documentation at all (go ahead, do a search for it). The documentation does mention the getElementsAtEvent function of the chart reference, but that is for Line Charts only.
I set an event listener (the right way) on my canvas element:
canv.addEventListener('click', handleClick, false);
...yet in my handleClick function, chart.getBarsAtEvent is undefined!
Now, in the Chart.js document, there is a statement about a different way to register the click event for the bar chart. It is much different than nnnick's comment on GitHub from 2 years ago.
In the Global Chart Defaults you can set an onClick function for your chart. I added an onClick function to my chart configuration, and it did nothing...
So, how the heck do I get the on-click-callback to work for my bar chart?!
Any help would be greatly appreciated. Thanks!
P.S.: I am not using the master build from GitHub. I tried, but it kept screaming that require is undefined and I was not ready to include CommonJS just so that I could use this chart library. I would rather write my own dang charts. Instead, I downloaded and am using the Standard Build version that I downloaded straight from the link at the top of the documentation page.
EXAMPLE: Here is an example of the configuration I am using:
var chart_config = {
type: 'bar',
data: {
labels: ['One', 'Two', 'Three'],
datasets: [
{
label: 'Dataset 1',
backgroundColor: '#848484',
data: [4, 2, 6]
},
{
label: 'Dataset 2',
backgroundColor: '#848484',
data: [1, 6, 3]
},
{
label: 'Dataset 3',
backgroundColor: '#848484',
data: [7, 5, 2]
}
]
},
options: {
title: {
display: false,
text: 'Stacked Bars'
},
tooltips: {
mode: 'label'
},
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [
{
stacked: true
}
],
yAxes: [
{
stacked: true
}
]
},
onClick: handleClick
}
};
I managed to find the answer to my question by looking through the Chart.js source code.
Provided at line 3727 of Chart.js, Standard Build, is the method .getElementAtEvent. This method returns me the "chart element" that was clicked on. There is sufficent data here to determine what data to show in a drill-down view of the dataset clicked on.
On the first index of the array returned by chart.getElementAtEvent is a value _datasetIndex. This value shows the index of the dataset that was clicked on.
The specific bar that was clicked on, I believe, is noted by the value _index. In my example in my question, _index would point to One in chart_config.data.labels.
My handleClick function now looks like this:
function handleClick(evt)
{
var activeElement = chart.getElementAtEvent(evt);
..where chart is the reference of the chart created by chart.js when doing:
chart = new Chart(canv, chart_config);
The specific set of data that was selected by the click can therefore be found as:
chart_config.data.datasets[activeElement[0]._datasetIndex].data[activeElement[0]._index];
And there you have it. I now have a datapoint that I can build a query from to display the data of the bar that was clicked on.
AUGUST 7TH, 2021. UPDATE
There is now a method for what we are looking for. Take a look at here
Hi this is the click event under options which is getting values from x and y-axis
onClick: function(c,i) {
e = i[0];
console.log(e._index)
var x_value = this.data.labels[e._index];
var y_value = this.data.datasets[0].data[e._index];
console.log(x_value);
console.log(y_value);
}
I found this solution at https://github.com/valor-software/ng2-charts/issues/489
public chartClicked(e: any): void {
if (e.active.length > 0) {
const chart = e.active[0]._chart;
const activePoints = chart.getElementAtEvent(e.event);
if ( activePoints.length > 0) {
// get the internal index of slice in pie chart
const clickedElementIndex = activePoints[0]._index;
const label = chart.data.labels[clickedElementIndex];
// get value by index
const value = chart.data.datasets[0].data[clickedElementIndex];
console.log(clickedElementIndex, label, value)
}
}
}
You can use onClick like this.
var worstCells3GBoxChart = new Chart(ctx, {
type: 'bar',
data: {
labels: lbls,
datasets: [{
label: 'Worst Cells by 3G',
data: datas,
backgroundColor: getColorsUptoArray('bg', datas.length),
borderColor: getColorsUptoArray('br', datas.length),
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
onClick: function (e) {
debugger;
var activePointLabel = this.getElementsAtEvent(e)[0]._model.label;
alert(activePointLabel);
}
}
});
Chartjs V3.4.1
This is what worked for me in v3, after looking at solutions for older versions:
const onClick = (event, clickedElements) => {
if (clickedElements.length === 0) return
const { dataIndex, raw } = clickedElements[0].element.$context
const barLabel = event.chart.data.labels[dataIndex]
...
}
raw is the value of the clicked bar.
barLabel is the label of the clicked bar.
You need to pass the onClick to the bar chart config:
const barConfig = {
...
options: {
responsive: true,
onClick,
...
}
}
Well done! This seems to return the data value being charted though, which in many cases might be possible to appear more than once, thus making it unclear what was clicked on.
This will return the actual data label of the bar being clicked on. I found this more useful when drilling down into a category.
chart_config.data.labels[activeElement[0]._index]
I was able to make this work in another way.
Might not be supported, but sometimes, I find that neither the label nor the value is adequate to get me the necessary information to populate a drill-through.
So what I did was add a custom set of attributes to the data:
var ctx = document.getElementById("cnvMyChart").getContext("2d");
if(theChart != null) {theChart.destroy();}
theChart = new Chart(ctx, {
type: typ,
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datakeys: ["thefirstone","thesecondone","thethirdone","thefourthone","thefifthone","thesixthone"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
...etc
Then when I need to push the drillthrough key into another ajax call, I was able to get it with this:
var theDrillThroughKey = theChart.config.data.datakeys[activePoints[0]._index];
So I'm really not sure that it's appropriate to be adding custom elements into the data for the Chart, but it's working so far in Chrome, IE and Firefox. I needed to be able to put more information into the drillthrough than I really wanted displayed.
Example of the full thing: https://wa.rrdsb.com/chartExamples
Thoughts?
I had the same problem with multiple datasets, and used this workaround:
var clickOnChart = function(dataIndex){
...
}
var lastHoveredIndex = null;
var chart_options = {
...
tooltips: {
...
callbacks: {
label: function(tooltipItem, chart) {
var index = tooltipItem.datasetIndex;
var value = chart.datasets[index].data[0];
var label = chart.datasets[index].label;
lastHoveredIndex = index;
return value + "€";
}
}
},
onClick:function(e, items){
if ( items.length == 0 ) return; //Clicked outside any bar.
clickOnChart(lastHoveredIndex);
}
}
Let's say that you declared a chart using a method like so:
window.myBar = new Chart({chart_name}, {
type: xxx,
data: xxx,
events: ["click"],
options: {
...
}
});
A good way of declaring onclick events would involve listening for the canvas click, like so:
({chart_name}.canvas).onclick = function(evt) {
var activePoints = myBar.getElementsAtEvent(evt);
// let's say you wanted to perform different actions based on label selected
if (activePoints[0]._model.label == "label you are looking for") { ... }
}
In the chart options for Chart.js v3.5.1 which is latest
Check below sample code
let enterpriseChartOptions = {
responsive:true,
maintainAspectRatio: false,
onClick: (c,i) => {
console.log('Get the underlying label for click,', c.chart.config._config.data.labels[i[0].index]);
},
plugins: {
title:{
text:'Enterprise Dashboard (Health Status of 10 stores) updated every 30 minutes',
fontSize:20
},
},
scales: {
x: {
display: true,
type: 'category',
position: 'right',
ticks: {
padding: 8,
},
},
y: {
display: true,
ticks: {
callback: function(val, index) {
// Show the label
return val < 1 ? "All good" : (val < 2 && val >=1) ? "Warning": val === 2 ? "Critical" : "";
},
//color: 'red',
stepSize: 1,
padding: 8
}
}
},
layout: {
padding: {
left: 20,
right: 20,
top: 25,
bottom: 0
}
},
};
var employeeDetailsCtx = document.getElementById("employee-details").getContext("2d");
var employee_details_data = {
labels: ["Late Present", "On Leave", "Training", "Tour"],
datasets: [{
label: "Officer",
backgroundColor: "#5A8DEE",
data: [
...
]
}, {
label: "Staff",
backgroundColor: "#4BC0C0",
data: [
...
]
}]
};
var myoption = {
tooltips: {
enabled: true
},
hover: {
animationDuration: 1
},
onClick: function (evt, i) {
var activePoint = employeeDetailsBarChart.getElementAtEvent(evt)[0];
var data = activePoint._chart.data;
var datasetIndex = activePoint._datasetIndex;
var label = data.datasets[datasetIndex].label;
var value = data.datasets[datasetIndex].data[activePoint._index];
e = i[0];
var x_value = this.data.labels[e._index];
console.log(x_value)
console.log(label)
console.log(value)
},
animation: {
duration: 1,
onComplete: function () {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.textAlign = 'center';
ctx.fillStyle = "rgba(0, 0, 0, 1)";
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 5);
});
});
}
}
};
var employeeDetailsBarChart = new Chart(employeeDetailsCtx, {
type: 'bar',
data: employee_details_data,
options: myoption
});
How do I hide the x-axis label/text that is displayed in chart.js ?
Setting scaleShowLabels:false only removes the y-axis labels.
<script>
var options = {
scaleFontColor: "#fa0",
datasetStrokeWidth: 1,
scaleShowLabels : false,
animation : false,
bezierCurve : true,
scaleStartValue: 0,
};
var lineChartData = {
labels : ["1","2","3","4","5","6","7"],
datasets : [
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [1,3,0,0,6,2,10]
}
]
}
var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Line(lineChartData,options);
</script>
UPDATE chart.js 2.1 and above
var chart = new Chart(ctx, {
...
options:{
scales:{
xAxes: [{
display: false //this will remove all the x-axis grid lines
}]
}
}
});
var chart = new Chart(ctx, {
...
options: {
scales: {
xAxes: [{
ticks: {
display: false //this will remove only the label
}
}]
}
}
});
Reference: chart.js documentation
Old answer (written when the current version was 1.0 beta) just for reference below:
To avoid displaying labels in chart.js you have to set scaleShowLabels : false and also avoid to pass the labels:
<script>
var options = {
...
scaleShowLabels : false
};
var lineChartData = {
//COMMENT THIS LINE TO AVOID DISPLAYING THE LABELS
//labels : ["1","2","3","4","5","6","7"],
...
}
...
</script>
This is for chart.js ^3.0.0
Remove x-axis labels and grid chart lines
var chart = new Chart(ctx, {
...
options:{
scales:{
x: {
display: false
}
}
}
});
Remove only x-axis labels
var chart = new Chart(ctx, {
...
options: {
scales: {
x: {
ticks: {
display: false
}
}
}
}
});
(this question is a duplicate of In chart.js, Is it possible to hide x-axis label/text of bar chart if accessing from mobile?)
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
}
}]
}
}
}
var lineChartData = {
labels: ["", "", "", "", "", "", ""] // To hide horizontal labels
,datasets : [
{
label: "My First dataset",
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: [28, 48, 40, 19, 86, 27, 90]
}
]
}
window.onload = function(){
var options = {
scaleShowLabels : false // to hide vertical lables
};
var ctx = document.getElementById("canvas1").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, options);
}
Faced this issue of removing the labels in Chartjs now. Looks like the documentation is improved.
http://www.chartjs.org/docs/#getting-started-global-chart-configuration
Chart.defaults.global.legend.display = false;
this global settings prevents legends from being shown in all Charts. Since this was enough for me, I used it. I am not sure to how to avoid legends for individual charts.
For those whom this did not work, here is how I hid the labels on the X-axis-
options: {
maintainAspectRatio: false,
layout: {
padding: {
left: 1,
right: 2,
top: 2,
bottom: 0,
},
},
scales: {
xAxes: [
{
time: {
unit: 'Areas',
},
gridLines: {
display: false,
drawBorder: false,
},
ticks: {
maxTicksLimit: 7,
display: false, //this removed the labels on the x-axis
},
'dataset.maxBarThickness': 5,
},
],
Inspired by christutty's answer, here is a solution that modifies the source but has not been tested thoroughly. I haven't had any issues yet though.
In the defaults section, add this line around line 71:
// Boolean - Omit x-axis labels
omitXLabels: true,
Then around line 2215, add this in the buildScale method:
//if omitting x labels, replace labels with empty strings
if(Chart.defaults.global.omitXLabels){
var newLabels=[];
for(var i=0;i<labels.length;i++){
newLabels.push('');
}
labels=newLabels;
}
This preserves the tool tips also.
The simplest solution is:
scaleFontSize: 0
see the chart.js Document
smilar question
If you want the labels to be retained for the tooltip, but not displayed below the bars the following hack might be useful. I made this change for use on an private intranet application and have not tested it for efficiency or side-effects, but it did what I needed.
At about line 71 in chart.js add a property to hide the bar labels:
// Boolean - Whether to show x-axis labels
barShowLabels: true,
At about line 1500 use that property to suppress changing this.endPoint (it seems that other portions of the calculation code are needed as chunks of the chart disappeared or were rendered incorrectly if I disabled anything more than this line).
if (this.xLabelRotation > 0) {
if (this.ctx.barShowLabels) {
this.endPoint -= Math.sin(toRadians(this.xLabelRotation)) * originalLabelWidth + 3;
} else {
// don't change this.endPoint
}
}
At about line 1644 use the property to suppress the label rendering:
if (ctx.barShowLabels) {
ctx.fillText(label, 0, 0);
}
I'd like to make this change to the Chart.js source but aren't that familiar with git and don't have the time to test rigorously so would rather avoid breaking anything.
UPDATE: chartjs ^4.2.0 + react-chartjs-2 ^5.2.0
Axis was removed.
const options = {
legend: {
display: false,
},
scales: {
x: {
display: false,
},
y: {
display: false,
},
},