This question is in continuation of this post Dynamically update values of a chartjs chart and the example http://jsbin.com/yitep/5/edit?html,js,output
I am new to chartJS, in the above example it is shown how to update dynamically chart data. But, can any one help me with how to start with a blank chart and then update dynamically.
Note: It is possible in Highcharts, is the same possible in chartJS.
EDIT
http://www.chartjs.org/docs/
The chartjs library is now the most updated and useful. Use the link above.
I think what you need to do is download the updated Chart.Js library, ChartNew.js at: https://github.com/FVANCOP/ChartNew.js/ . This updated library has an update function among many other improvements that make things much easier. You can download the zip file using the link above and find tons great example files that will help you figure out most issues. There is also some pretty good documentation at: https://github.com/FVANCOP/ChartNew.js/wiki/100.Available_options .
I will add a full example from the above library that you can copy and paste into an html file in order to see exactly how you can create a dynamic chart. Just take a look and play around with the examples until you start to see how things work.
<!doctype html>
<!--[if lte IE 8]><SCRIPT src='source/excanvas.js'></script><![endif]--><SCRIPT src='../ChartNew.js'></script>
<SCRIPT src='../Add-ins/format.js'></script>
<SCRIPT>
function setColor(area,data,config,i,j,animPct,value)
{
if(value > 35)return("rgba(220,0,0,"+animPct);
else return("rgba(0,220,0,"+animPct);
}
var charJSPersonnalDefaultOptions = { decimalSeparator : "," , thousandSeparator : ".", roundNumber : "none", graphTitleFontSize: 2 };
defCanvasWidth=600;
defCanvasHeight=300;
var mydata = {
labels : [],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointstrokeColor : "yellow",
xPos : [],
data : [],
title : "2014"
}
]
}
var startWithDataset =1;
var startWithData =1;
var opt = {
animationStartWithDataset : startWithDataset,
animationStartWithData : startWithData,
animation : true,
animationLeftToRight : true,
animationSteps : 20,
animationEasing: "linear",
canvasBorders : true,
canvasBordersWidth : 3,
canvasBordersColor : "black",
graphTitle : "animation With Update",
legend : true,
// inGraphDataShow : true,
annotateDisplay : true,
onAnimationComplete : startUpdate,
graphTitleFontSize: 18,
responsive : true,
scaleOverride: true,
scaleSteps: 10,
scaleStepWidth: 10,
scaleStartValue: 0,
fmtXLabel : "fmttime hh:mm:ss",
animationCount: 1,
animationPauseTime : 0,
animationBackward: true
};
function startUpdate(ctx, config, data, tp, count) {
setTimeout(function (){updt(ctx,data,config);}, 1000+Math.random()*500);
// setTimeout(function (){updt(ctx,data,config);}, 1000);
};
function updt(ctx,data,config) {
updtData(data);
config.animationSteps = 50*data.datasets[0].xPos.length;
config.animationStartValue=1-(2/data.datasets[0].xPos.length);
deleteHighLight(ctx,data);
updateChart(ctx,data,config,true,true);
}
function updtData(data) {
var i;
var t=new Date();
var coeff = 1000 ;
var rounded = new Date(Math.round(t.getTime() / coeff) * coeff + coeff);
for(i=0;i<10;i++)
{
var t2 = new Date(rounded - (18-2*i) * 1000);
data.labels[i]=t2;
}
data.xBegin=data.labels[0];
data.xEnd=data.labels[9];
data.datasets[0].xPos[data.datasets[0].xPos.length]=t;
vl=Math.random()*100;
data.datasets[0].data[data.datasets[0].data.length]=vl;
// remove data outside first time;
while(data.datasets[0].xPos[0]<data.labels[0]) {
data.datasets[0].xPos.splice(0,1);
data.datasets[0].data.splice(0,1);
}
}
updtData(mydata);
updtData(mydata);
updtData(mydata);
mydata.datasets[0].xPos[0]=new Date(mydata.datasets[0].xPos[0]-2000);
mydata.datasets[0].xPos[1]=new Date(mydata.datasets[0].xPos[1]-1000);
</SCRIPT>
<html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<head>
<title>Demo ChartNew.js</title>
</head>
<body>
<center>
<FONT SIZE=6><B>Demo of ChartNew.js !</B></FONT> <BR>
<script>
document.write("<canvas id=\"canvas_Line\" height=\""+defCanvasHeight+"\" width=\""+defCanvasWidth+"\"></canvas>");
window.onload = function() {
var myLine = new Chart(document.getElementById("canvas_Line").getContext("2d")).Line(mydata,opt);
}
</script>
</body>
</html>
The provided code example is taken directly from the GitHub download folder. They provide a great deal of examples to help make sense of the the documentation.
Check out this simple example I wrote in jsfiddle. I first created a bar chart and then used chart.update()method to update it in every second.
//value for x-axis
var emotions = ["calm", "happy", "angry", "disgust"];
//colours for each bar
var colouarray = ['red', 'green', 'yellow', 'blue'];
//Let's initialData[] be the initial data set
var initialData = [0.1, 0.4, 0.3, 0.6];
//Let's updatedDataSet[] be the array to hold the upadted data set with every update call
var updatedDataSet;
/*Creating the bar chart*/
var ctx = document.getElementById("barChart");
var barChart = new Chart(ctx, {
type: 'bar',
data: {
labels: emotions,
datasets: [{
backgroundColor: colouarray,
label: 'Prediction',
data: initialData
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
min: 0,
max: 1,
stepSize: 0.5,
}
}]
}
}
});
/*Function to update the bar chart*/
function updateBarGraph(chart, label, color, data) {
chart.data.datasets.pop();
chart.data.datasets.push({
label: label,
backgroundColor: color,
data: data
});
chart.update();
}
/*Updating the bar chart with updated data in every second. */
setInterval(function() {
updatedDataSet = [Math.random(), Math.random(), Math.random(), Math.random()];
updateBarGraph(barChart, 'Prediction', colouarray, updatedDataSet);
}, 1000);
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>
<body>
<div>
<h1>Update Bar Chart</h1>
<canvas id="barChart" width="800" height="450"></canvas>
</div>
<script src="barchart.js"></script>
</body>
</head>
</html>
Hope this helps.
Related
how do I make the values in Chart JS update as the bar progresses?
For example, I want the values for each bar to start at 0 and count up to there value, stopping when the bar has reached it's height.
At the moment, it just displays it's full value upon animation start (when the page loads)
Chart JS docs:
https://www.chartjs.org/
Here is a plugin I found:
https://emn178.github.io/chartjs-plugin-labels/samples/demo/
Here is a JS Fiddle (ignore the shaking!)
https://jsfiddle.net/8uehq5xr/
<!doctype html>
<html>
<head>
<title>Horizontal Bar Chart</title>
<script src="../../node_modules/chart.js/dist/Chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.7.3/dist/Chart.min.js">
</script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-
labels/src/chartjs-plugin-labels.js"></script>
</head>
<body>
<canvas id="bar-chart" width="800" height="450"></canvas>
<div id="value">100</div>
<Script>
// Bar chart
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: ["Africa", "Asia", "Europe", "Latin America", "North America"],
datasets: [
{
label: "Population (millions)",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: [2478,5267,734,784,433]
}
]
},
options:
{
plugins: {
labels:
{
render: 'value',
fontSize: 20,
}
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
display: false
}],
},
tooltips: { enabled: true},
hover: {animationDuration: 1},
}
});
</script>
</body>
</html>
I assume you would like something like a fast counter synchronized with chart drawing, can't you do it with just a for loop refreshing data given to chart.js until you reach their real value ?
No need for a plugin if it's a that small improvement you need
Example:
final data is [2478,5267,734,784,433]
initial data is [0, 0, 0, 0, 0]
1°) set an interval incrementing data of 1/10 of their value by example, each 200ms
-> after 200ms you now have [247, 526, 73, 78, 43]
2°) cancel interval once you reached final data
You can then play with interval and increment steps (1/100 in stead of 1/10 by example)
Here is a workaround (but I bet you block with chart drawing ?)
const currentData = [0,0,0,0,0];
const finalData = [2478,5267,734,784,433];
const stepTick = 0.1;
let stepNumber = 1;
const redrawingAfter1Step = setInterval(() => {
for(let i = 0; i < currentData.length; i++) {
currentData[i] = stepTick * stepNumber * finalData[i];
}
drawChart(currentData);
if ((stepNumber * stepTick) === 1) {
clearInterval(redrawingAfter1Step);
}
stepNumber++;
}, 500);
I'm currently working with Chart.js, and I need to change between two differents datasets. To do this I just change the dataset and use the Update function.
The main problem is that when you change multiple times between the datasets, the animation dissapears and it looks horrible.
Here you can see what I'm talking about and my code.
Does somebody know how could I fix it?
Thanks a lot!
And here is my code, in case the link doesn't work:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Chart.js Example</title>
<!-- import plugin script -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js'></script>
</head>
<body>
<!-- bar chart canvas element -->
<canvas id="chart" width="600" height="400"></canvas>
<button onclick="manageCharts()" id="chartDataButton">Chart 2</button>
</body>
</html>
And the javascript code
Chart.defaults.global.responsive = false;
var chartData1 = {
labels : ["L1", "l2", "l3", "l4"],
datasets : [{
label: "LEGEND",
data : [13, 23, 9, 4],
backgroundColor: "#FF88CC",
borderColor: "#000000",
borderWidth: 1,
}]
}
var chartData2 = {
labels : ["L11", "L12"],
datasets : [{
label: '{{ legend }}',
data : [7, 1],
backgroundColor: "#FEFE65",
borderColor: "#00FFFF",
borderWidth: 2,
}]
}
var pieChartOptions = {
rotation: -Math.PI,
cutoutPercentage: 30,
circumference: Math.PI,
legend: {
position: 'left'
},
animation: {
animateRotate: true,
animateScale: false
}
};
// get chart canvas
var ctx = document.getElementById("chart").getContext("2d");
var pieChart = new Chart(ctx, {
type: 'pie',
data: chartData1,
options: pieChartOptions
});
function manageCharts(){
var button = document.getElementById("chartDataButton");
var previousData = pieChart.config.data;
if(previousData == chartData1){
button.textContent = "Chart 1";
showChart2Data();
}else if(previousData == chartData2){
button.textContent = "Chart 2";
showChart1Data();
}
}
function showChart2Data(){
pieChart.config.data = chartData2;
pieChart.update();
};
function showChart1Data(){
pieChart.config.data = chartData1;
pieChart.update();
};
I've updated your code in this jsfiddle to use the destroy() function.
Using update() doesn't seem reset the animation.
Using destroy() removes the chart and then your code will recreate the new chart (and animation)
PS: Sorry for changing to jsfiddle from JS Bin. I was having troubles editing in JS Bin.
Chartjs is a pretty excellent open source tool, but had a quick question about a bar chart I'm trying to create. Given this chart data:
var chartData = {
labels : labels,
datasets :[
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
scaleOverride: true,
scaleSteps: 9,
data : values
}
]
}
I had hoped that the chart would draw with top value of 10, whether or not there were any values of 10. I thought the scaleOverride and scaleSteps would accomplish that.
Is it possible to get that output? I went thru the docs and did not see any other obvious options to set.
Update
got it to work. My orig post did not include the javascript function at the bottom.
<div class="barChartTest" id="rating_12229" onload="drawChart();">
<input type="hidden" class="rating-component" comp-name="test1" comp-value="6"/>
<input type="hidden" class="rating-component" comp-name="test2" comp-value="7"/>
<input type="hidden" class="rating-component" comp-name="test3" comp-value="6"/>
<input type="hidden" class="rating-component" comp-name="test4" comp-value="5"/>
<input type="hidden" class="rating-component" comp-name="test5" comp-value="1"/>
</div>
<canvas id="rating_12229" width="50" height="20"></canvas>
and here is my javascript:
function buildRatingChartData(ratingId){
var comps = document.getElementById(ratingId).getElementsByClassName("rating-component");
var labels = [];
var values = [];
for(var i=0; i<comps.length; i++){
labels.push(comps[i].getAttribute("comp-name"));
values.push(comps[i].getAttribute("comp-value"));
}
var chartData = {
labels : labels,
datasets :[
{
scale: 10,
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
scaleOverride:true,
scaleSteps:9,
scaleStartValue:0,
scaleStepWidth:1,
data : values
}
]
}
return chartData;
}
here was where I added those options and got the output I wanted:
function drawCharts(){
var ratings = document.getElementsByClassName("brewRatingData");
for(var i=0; i<ratings.length; i++){
var ratingId = ratings[i].getAttribute("id");
var canvasId = ratingId.replace("brewRating", "coffeeBarChart");
var brewChartData = buildRatingChartData(ratingId);
var ctx = document.getElementById(canvasId).getContext("2d");
window.myBar = new Chart(ctx).Bar(brewChartData, {
responsive : true,
scaleOverride:true,
scaleSteps:10,
scaleStartValue:0,
scaleStepWidth:1,
});
}
}
Also include scaleStartValue and scaleStepWidth as stated in docs.
Example
This example creates a bar chart with Y-axis starting at 0 and ending at 900. To do that, step width is set to 100 and number of steps are set to 9.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<canvas id="income" width="600" height="400"></canvas>
</body>
</html>
JS
var barData = {
labels : ["January","February","March","April","May","June"],
datasets : [
{
fillColor : "#48A497",
strokeColor : "#48A4D1",
data : [456,479,324,569,702,600]
},
{
fillColor : "rgba(73,188,170,0.4)",
strokeColor : "rgba(72,174,209,0.4)",
data : [364,504,605,400,345,320]
}
]
};
var income = document.getElementById("income").getContext("2d");
new Chart(income).Bar(barData, {
animation:false,
scaleOverride:true,
scaleSteps:9,
scaleStartValue:0,
scaleStepWidth:100
});
var myChart = new Chart(ctx, {
type: 'bar',
data:data,
options: {
responsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
steps: 10,
stepValue: 6,
max: 60 //max value for the chart is 60
}
}
}]
}
}
});
#2.8.0
custom y-axis setup. You only need range min/max and with stepSize you control the axis.
...
yAxes: [{
ticks: {
stepSize: 0.1,
min: 2,
max: 2.5
},
gridLines: {
display: false
},
stacked: false
}]
...
For those who struggle with react-chartjs-2:
Example that starts from 0, makes 2 steps each of size 20 and goes up to max
let options = {
scales: {
y: {
ticks: {
beginAtZero: true,
steps: 2,
stepSize: 20,
max: 40
}
}
}
}
Usage:
// ... your component structure
return <Line options={options} />
I have set up a simple column chart in Highcharts 4 with jQuery 1.9.1 where I parse a CSV file. I get the normal page showing with the column chart, but when I click on a bar nothing happens. I actually do see the arrays being created in the console (IE11) and they appear to be just what I need, they are in the correct syntax and the IDs match.
The JS fiddle [was...://jsfiddle.net/tjxwty3y/ ... I have changed this in the edit at the bottom ] . I put an example of the CSV that I use, but do not know how to link an external one into the JS Fiddle. I have tried the examples with CSV/TSVs embedded in the code and they have worked, so I think it has to do with how I am pushing the data, hence the external reference.
The CSV is very simple. I have the 3 categories in the first column, their values for the front chart, followed by the IDs in the 3rd and finally the drilldown values in the 4th and 5th.
CSV looks like this
AREA,VALUE,TYPE,SHIFT1,SHIFT2
Blog1,50000,Blog1_Shift,5,6
Blog2,60000,Blog2_Shift,2,3
Blog3,40000,Blog3_Shift,7,8
I have looked at multiple posts (and some videos) where the CSV or TSV is within the JS Fiddle and on Highcharts website, but I completely am not seeing where I have gone wrong (and I know that I have).
Just in case, here is the raw data from js fiddle which has the libraries (I typically use Higcharts 4 and JQuery 1.11 but here I've modified some older code that used JQuery 1.9.1):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="http://code.highcharts.com/highcharts.js"></script>
<script type='text/javascript' src="http://code.highcharts.com/modules/data.js"></script>
<script type='text/javascript' src="http://code.highcharts.com/modules/drilldown.js"></script>
<style type='text/css'></style>
<script type='text/javascript'>
//<![CDATA[
$(window).load(function () {
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'My Title Here'
},
xAxis: {
categories: [],
name: []
},
yAxis: {
title: {
text: 'Value Here'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
y: 15,
borderWidth: 0,
itemStyle: {
color: '#333',
fontSize: '15px',
},
navigation: {
activeColor: '#3E576F',
animation: true,
arrowSize: 12,
inactiveColor: '#CCC',
style: {
fontWeight: 'bold',
color: '#333',
fontSize: '15px',
}
}
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
marker: {
lineWidth: 1
}
}
},
series: [],
drilldown: []
};
$.get("http://my/csv/notvalid/dev_drilldown4.csv", function (csvData) {
var lines = csvData.split('\n');
var series = {
data: [],
visible: true,
type: 'column',
colorByPoint: true,
drilldown: true
};
var drilldown = {
series: []
};
$.each(lines, function (lineNo, line) {
if (lineNo > 0 && lineNo < 4) {
var items = line.split(',');
var seriesname = String(items[0]); // this is the area
var area_cost = parseFloat(items[1]); // this is the data for the rollup
var drill_id = String(items[2]); // this will be the id of the drilldown
var shift_one_value = parseFloat(items[3]); // shift1 value
var shift_two_value = parseFloat(items[4]); // shift2 value
series.data.push({
name: seriesname,
y: area_cost,
drilldown: drill_id
});
drilldown.series.push({
id: drill_id,
data: [["shift1", shift_one_value],["shift2", shift_two_value]]
});
}
});
console.log(series.data);
console.log(drilldown.series);
options.series.push({ data: series.data });
options.drilldown.push({ series: drilldown.series });
var chart = new Highcharts.Chart(options);
});
});
});
</script>
</head>
<body>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
I appreciate any for help/advice.
Thanks
EDIT:
Now that I have added in Salman's and Pawell's edits, including adding in the CSV to the jsFiddle (see Pawell's jsFiddle for what it now looks like) I encountered an additional issue, but it is/was working now!
I realized I forgot the "name" of the series and added that in, adjusting the 'var series' and changing the 'series.data.push' to 'series.push' and watched the log as mentioned by Salman. Now nothing appears, but the console log appears to show the data with the names, ids and data, but no chart (and no error).
The js fiddle is: http://jsfiddle.net/5jzb8hzb/1/. Would you know why changing the 'series.data.push' caused the initial chart to not render?
As noticed by #Salman, there is a couple of issues:
first load Highcahrts then drilldown.js (issue only in jsFiddle)
you shouldn't push to the drilldown array, but assign created series
you have drilldown: [], while should be drilldown: {}
for series you have options.series.push({ data: series.data }), while simply use options.series.push(series) or options.series = [series]
Extra note: I suggest to check values if those are not NaN's - sometimes editors create extra empty new line at the end of the file.
After all fixes, here is fully working code: http://jsfiddle.net/tjxwty3y/7/
Minimized example:
var options = {
chart: {
renderTo: 'container'
},
series: [],
drilldown: {}
};
var csvData = document.getElementById("data").innerHTML; // like $.get()
var lines = csvData.split('\n');
var series = {
data: [],
visible: true,
type: 'column',
colorByPoint: true,
drilldown: true
};
var drilldown = {
series: []
};
// I know with the below I get an extra line so can deal with that when I get the rest of the data sorted
$.each(lines, function (lineNo, line) {
if (lineNo > 0 && lineNo < 4) {
var items = line.split(',');
var seriesname = String(items[0]); // this is the area name
var area_cost = parseFloat(items[1]); // this is the data for the area rollup
var drill_id = String(items[2]); // this will be the id of the drilldown
var shift_one_value = parseFloat(items[3]); // drilldown shift1 value
var shift_two_value = parseFloat(items[4]); // drilldown shift2 value
if(!isNaN(area_cost) && !isNaN(shift_one_value) && !isNaN(shift_two_value)) {
series.data.push({
name: seriesname,
y: area_cost,
drilldown: drill_id
});
drilldown.series.push({
id: drill_id,
data: [
["shift1", shift_one_value],
["shift2", shift_two_value]
]
});
}
}
});
options.series = [series];
options.drilldown = drilldown;
var chart = new Highcharts.Chart(options);
There is a bug in the code; if you log options you will detect it. drilldown configuration is supposed to have a series key. But in your case the key is inside drilldown[0]; probably because of using push function.
The code worked after I changed
options.drilldown.push({ series: drilldown.series });
to
options.drilldown.series = drilldown.series;
There was also another bug- drilldown library should be loaded after highcharts.
Edit: Updated fiddle: http://jsfiddle.net/dxann41x/1/
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,
},
},