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} />
Related
My charts are changing its alignments due to the size of X-axis label names. The angle of the names also change in order to make it fit in the view. I do not want any changes in the graph alignments (which I believe is due to names printed in an angle) and also want the names in X-Axis to print normally. Graph wrong alignment images.
I have tried using the maxRotation and minRotation to 90 but here all the values are tilted to 90. I want this to be made dynamic ie. the angle must be either 0 or 90 (if the program wants to change angle).
Chartjs code
scales: {
y: {
beginAtZero : false,
ticks: {
display: false,
},
grid : {
display : false,
drawTicks : false,
drawBorder: false
},
},
x: {
maxBarThickness: 10,
ticks : {
color: 'black',
maxRotation: 90,
minRotation: 0,
autoSkip: false,
fontSize : 10,
},
grid : {
display : false,
drawTicks : false
}
}
}
HTML code to hold charts
<style>
.first {
float : left;
width: 45%;
margin: 10px;
}
</style>
<div class ="first"> <canvas id="Services"></canvas> </div>
<div class ="first"> <canvas id="VPN"> </canvas> </div>
<div class = "first"> <canvas id="Policy ID"></canvas> </div>
<div class = "first"> <canvas id="Source Country"></canvas> </div>
<div class = "first"> <canvas id="Source IP"> </canvas> </div>
<div class = "first"> <canvas id="Destination IP"></canvas> </div>
How do I achieve this where I can change the tilt angle to 90 if required ?
You can dynamically change it in the chart config itself and then call update on the chart like so:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {
scales: {
x: {
ticks: {
minRotation: 0,
maxRotation: 0
}
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
document.getElementById("switch").addEventListener("click", () => {
chart.options.scales.x.ticks.minRotation = chart.options.scales.x.ticks.minRotation === 0 ? 90 : 0;
chart.options.scales.x.ticks.maxRotation = chart.options.scales.x.ticks.maxRotation === 0 ? 90 : 0;
chart.update();
});
<body>
<button id="switch">
Switch tick rotation
</button>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>
I am working on a webpage that presents dashboard on th basis of invoice processing project.
using below code i am populating bar chart.
function loadVolumeChart()
{
var pieChartContent = document.getElementById('chartAreaWrapper');
pieChartContent.innerHTML = '';
$('#chartAreaWrapper').append('<canvas id="line-chart" height="300" width="1500px"><canvas>');
//getData For Volume Analysis Chary
var url_string = document.referrer;;
var url = new URL(url_string);
var name = url.searchParams.get("name");
var user=url.searchParams.get("user");
var team=url.searchParams.get("team");
var date=url.searchParams.get("date");
var dates = [];
var count = [];
var from = date.split("-")[0];
var to = date.split("-")[1];
var re=$.ajax({
url: 'getTotalCounts.php',
type: 'POST',
data: {
from:from,
to:to,
team:team,
totalVolume: '00'
},
async:false,
success: function(data) {
var result =data;
var json = JSON.parse(result);
dates=json[0].data;//json[0].data;
count=json[1].data;
//alert(dates);
}
}).done(function(data){
// openPage(data);
}).fail(function(data){
alert(data.responseText);
});
//volume chart
new Chart(document.getElementById("line-chart"), {
type: 'bar', //line
data: {
labels:dates,
datasets: [{
data:count,
label: "Total Inward",
backgroundColor: "#0E6655", //borderColor
fill: true
},
]
},
options: {
responsive:false,
maintainAspectRatio: true,
legend: {
display: false
},
tooltips: {
enabled: true
},
scales: {
xAxes: [{
gridLines: {
display:false
},
barThickness: 15,
}],
yAxes: [{
barPercentage: 1.0,
categoryPercentage: 1.0,
gridLines: {
display:false
},
ticks: {
min: 0,
max:10,
stepSize: 1
}
}]
},
}
});
//end of volume chart
}
But the problem is when data is low, means if the x axis data contains only 2 dates, then the gap between two bars is too large, like the image below,
but if i add more dates then the gap reduces.i want to set gap between two bars even if their are only two bars. the gap between both should not increase if the dates (bars) according to the size of x axis data. if the data is large then it should only scroll. thats why i have added scroll bar.
the div of chart is as:
<div class="parentDiv" >
<div class="chartAreaWrapper" id="chartAreaWrapper" style="height:80%;width:70%;margin-left: 20px; margin-top: 10px;float: left;">
<canvas id="line-chart" height="300" width="1500px"></canvas>
</div>
</div>
In your code, the option xAxis.barThickness defines that the width of individual bars has to be of 15 pixels. Simply remove this option.
You should also consider to use the latest stable version of Chart.js (currently v2.9.3) where the option xAxis.barThickness is deprecated. The options barThickness, barPercentage and categoryPercentage are now part of the dataset configuration.
I am using chartjs script to display a bar chart. Displayed the views and visitors bars and overlapped it on one another. Now I want to reduce the width of the resultant bar and on the clickEvent of the bar stroke should another div get changed which is having proper values from a database. I have gone through all queries related with chartjs on StackOverflow, but failed to implement it.
This is what I have tried:
<canvas id="barChart" style="height:5px; width:30px;" ></canvas>
script=>
/* javascript to show bar chart for weekly analysis */
$(function () {
var areaChartData = {
labels : ['Nov-15', 'Nov-22', 'Nov-29', 'Dec-06','Dec-13', 'Dec-19']
datasets: [
{
label : 'Total View Count',
fillColor : '#0087be',
strokeColor : '#0087be',
pointColor : '#0087be',
pointStrokeColor : '#0087be',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
barPercentage : 0.5,
data : [1, 3, 2,2, 7,2,]
},
{
label : 'Total Visitors Count',
fillColor : 'rgba(60,141,188,0.9)',
strokeColor :'rgba(60,141,188,0.8)',
pointColor : '#3b8bba',
pointStrokeColor : 'rgba(60,141,188,1)',
pointHighlightFill : '#fff',
pointHighlightStroke : 'rgba(60,141,188,1)',
barPercentage : 0.5,
data : [1, 2, 1, 2, 4, 2]
},
],
}
var barChartCanvas = $('#barChart').get(0).getContext('2d')
var barChart = new Chart(barChartCanvas)
var barChartData = areaChartData
barChartData.datasets[1].fillColor = '#004069'
barChartData.datasets[1].strokeColor = '#004069'
barChartData.datasets[1].pointColor = '#004069'
var barChartOptions = {
options: {
scales: {
xAxes: [{
barPercentage: 1,
categoryPercentage: 0.5 / 10 * barChartData.datasets[0].data.length }],
yAxes: [{
ticks: {
beginAtZero:true
}
}],
}
},
//Boolean - Whether the scale should start at
zero, or an order of magnitude down from the lowest value
barStrokeWidth : 2,
barValueSpacing : 15,
barDatasetSpacing : -175,
datasetStroke : true,
barDatasetWidth : -10,
dataPointMaxWidth : 20,
responsive : true,
maintainAspectRatio : true,
}
barChartOptions.datasetFill = false;
barChart.Bar(barChartData, barChartOptions)
});
[bar image shown in picture want to reduce bar stroke width. Two
bars are having different blue color shed][1]
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.
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,
},
},