Chart.js axes always show zero - javascript

I'm using Chart.js for a simple bar graph with data read from mysql. Unfortunately, the y-axis starts at random numbers, often higher than some of the bars. Therefore, some bars are not visible, although their value should be high enough:
I've already used the scaleBeginAtZero: true-option as suggested here, to no avail:
var ctx = $("#mycanvas");
Chart.defaults.global.scaleBeginAtZero = true;
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: {
scaleBeginAtZero: true
}
});
Any ideas? The complete code is available here.

Well you can use the below code. So that, Y Axes of your bar chart starts from zero.
options: {
scales : {
yAxes : [{
ticks : {
beginAtZero : true
}
}]
}
}
[Sample-Code]
var ctx = document.getElementById("myChart1");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1,
data: [65, 59, 80, 81, 56, 55, 40],
}
]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales : {
yAxes : [{
ticks : {
beginAtZero : true
}
}]
}
}
});

Related

ChartJS Only Show Large Font Size for a Specific Tick

I am attempting to emphasize a specific value on the X-Axis if it meets a specific condition.
For example, in my codepen I want to only change the font size of the 'blue' bar. Is this even possible with Chart.js?
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}],
xAxes: [{
ticks: {
//only show large font size for 'Blue'
fontSize: 16
}
}]
}
}
});
Chartjs doesn't have a public api to do this but you can modify internal _ticks on beforeDraw and make the label "Blue" as major: true then that label will be drawn using the major styling in tick configuration options.
Also use this with caution since it relies on internal implementation and thus might break in future releases (very unlikely to happen but just saying).
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}],
xAxes: [{
ticks: {
fontSize: 16,
major: {
fontSize: 20
}
}
}]
}
},
plugins: [{
beforeDraw: function({ chart }, options) {
chart.boxes
.find(box => box.id === "x-axis-0")
._ticks
.find(tick => tick.label === "Blue")
.major = true;
}
}]
});
<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
PS: Just in case someone is wondering how I know this internal implementation I searched fillText in chartjs github source code and console.log(myChart) xD
Looks like it's not possible according to their docs. You can only do something like uppercase needed label with callback function
xAxes: [{
ticks: {
fontSize: 16,
callback: v => v === 'Blue' ? v.toUpperCase() : v
}
}]
For chartjs 3.0 and higher, it can be done by using scriptable-options. Include it like this into your options for ticks:
options: {
scales: {
x: {
ticks: {
font: {
size: (c) => {
if (c.index==1){
return 20 // at tick label with idx one set fontsize 20
}
else {
return 12 // for all other tick labels set fontsize 12
}
},
},
},
},
},
},

Chart.js - Thousand separator, currency in tool-tips, X & Y Axes labels

I'm new to Chart.js and I've been trying to get all the snippets I've found to work together to get my labels and tool-tips to display correctly. I thought I would post my working script to show how I managed to get my values displayed with the thousand separator, a currency symbol added to the tool-tips and to the scales, and to have labels on the X and Y axes. Some of the posts I saw didn't have examples on where to place the relevant code.
Please note, I did not write all this code. This has been compiled from multiple Stack searches and multiple attempts to get some of it to work together.
Here's the code I used...
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["July", "August", "September", "October", "November", "December", "January", "February", "March", "April", "May", "June"],
datasets: [{
label: 'YTD 2017/18',
data: ["12000, 11250, 10000, 2000, 3000, 6000,12000, 11250, 10000, 2000, 3000, 6000"],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Total Sales',
fontStyle: 'bold',
fontSize: 20
},
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
if(parseInt(value) >= 1000){
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Months of the Year',
fontStyle: 'bold',
fontSize: 20
}
}],
},
tooltips: {
callbacks: {
// this callback is used to create the tooltip label
label: function(tooltipItem, data) {
// get the data label and data value to display
// convert the data value to local string so it uses a comma seperated number
var dataLabel = data.labels[tooltipItem.index];
// add the currency symbol $ to the label
var value = ': $ ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();
// make sure this isn't a multi-line label (e.g. [["label 1 - line 1, "line 2, ], [etc...]])
if (Chart.helpers.isArray(dataLabel)) {
// show value on first line of multiline label
// need to clone because we are changing the value
dataLabel = dataLabel.slice();
dataLabel[0] += value;
} else {
dataLabel += value;
}
// return the text to display on the tooltip
return dataLabel;
}
}
},
}
});
</script>

Pagination in Bar chart using ChartJS

I am using chartJS for display some data with Bar Chart. there are some issues with chartJs. When i have to much data-filed for example 100 or more data-field and it have long lasting label its looks like ugly.
how to config bar chart ?
here is my bar chart screenshot
here is my FIDDLE
in above example i have 100 data-filed, can i paginate this bar-chart ?
here is my code
var lbl = [];
var dt = [];
for(var i = 1;i<=100;i++){
lbl.push("this_is_my_lable_name_"+i);
}
for(var i = 1;i<=100;i++){
dt.push(Math.floor((Math.random() * 100) + 1));
}
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: lbl,
datasets: [{
label: '# of Votes',
data: dt,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
You can try this solution to consider the chart scroll like this:
Clone a different canvas for y axis so that when you scroll then only bars will appear to move
Adding the canvas for y axis
<canvas id="myChartAxis" height="600" width="0"></canvas>
Now cloning the axis
var sourceCanvas = myLiveChart.chart.canvas;
var copyWidth = myLiveChart.scales['y-axis-0'].width - 10;
var copyHeight = myLiveChart.scales['y-axis-0'].height + myLiveChart.scales['y-axis-0'].top + 10;
var targetCtx = document.getElementById("myChartAxis").getContext("2d");
targetCtx.canvas.width = copyWidth;
targetCtx.drawImage(sourceCanvas, 0, 0, copyWidth, copyHeight, 0, 0, copyWidth, copyHeight);
For a Demo see this FIDDLE
For better visualization its better to avoid labels in x axis and show this info intuitive via tool tip anyhow
You could wrap the canvas with a wrapper class and change its width accordingly which suites you the best. also, if you don't want the chart to cover entire screen, you can wrap it with another wrapper class.
var lbl = [];
var dt = [];
for (var i = 1; i <= 100; i++) {
lbl.push("this_is_my_lable_name_" + i);
}
for (var i = 1; i <= 100; i++) {
dt.push(Math.floor((Math.random() * 100) + 1));
}
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: lbl,
datasets: [{
label: '# of Votes',
data: dt,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
.wrapper {
width: 600px;
height: 400px;
overflow-x: scroll;
}
.chartWrapper {
width: 6000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<div class="wrapper">
<div class="chartWrapper">
<canvas id="myChart" height="19"></canvas>
</div>
</div>
JSFiddle

chart.js color not rendering

I am trying to use chart.js to create a simple live line/scatter chart, z-indexed to act as a backdrop for my app. For some reason, it's rendering as an opaque gray color instead of the reddish color I've specified. And, even though I've tried changing the other chart elements and defaults the chart is always gray. I'm sure it's a trivial fix but just i can not figure it out.
Here is the link to a JS Bin that has the full code.(You'll need to set and start the timer before the chart will have any data to show) Also, more specifically, this is the JS code related to creating the chart:
var ctx = document.getElementById('canvas').getContext("2d"),
points = [{x:0,y:0}],
lineData = {
datasets: [{
fillColor: "rgba(217, 108, 99, .9)",
strokeColor: "rgba(255, 255, 255, 1)",
pumpntHighlightStroke: "rgba(220,220,220,1)",
data: points
}]
},
lineOptions = {
showScale: false,
scaleShowLabels: false,
scaleShowGridLines : false,
pointDot : false,
pointDotRadius : 0,
pointDotStrokeWidth : 0,
pointHitDetectionRadius : 0,
datasetStroke : true,
datasetStrokeWidth : 3,
datasetFill : true,
};
Chart.defaults.global.elements.point.radius = 0;
Chart.defaults.global.legend.display = false;
Chart.defaults.global.tooltips.enabled = false;
Chart.defaults.global.animation.duration = 250;
Chart.scaleService.updateScaleDefaults('linear', {
display: false,
ticks: {
beginAtZero: true,
min: 0
}
});
Chart.defaults.global.elements.line.tension = 0.05;
Chart.defaults.global.maintainAspectRatio = false;
myChart = new Chart(ctx, {
type: 'scatter',
data: lineData,
options: lineOptions
});
Thank you for your time. please let me know if there is anything further I can explain.
I think this is because you don't use the correct properties. According to the docs (http://www.chartjs.org/docs/), you should use backgroundColor, not fillColor.
See the first example in the doc: http://www.chartjs.org/docs/#getting-started-creating-a-chart
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
Note that strokeColor doesn't exist aswell.

Updating chart.js bar graph in real time

I am using Chart.js to create a simple bar chart with only two rows and 2 sets of data. I am new to using the library and after reading the examples, I feel comfortable with most of the things there. Here is what I have so far
JS code for graph:
var helpers = Chart.helpers;
var canvas = document.getElementById('bar');
var barChartData = {
labels: ["IBM", "Microsoft"],
datasets: [{
label: "Product A",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
data: [25, 75]
}, {
label: "Product B",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
data: [75, 25]
}]
}
//
var bar = new Chart(canvas.getContext('2d')).Bar(barChartData, {
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>kb",
animation: false,
})
;
Now, I was wondering if it is possible to update this graph if the data was changed in real time without refreshing the page. For instance if every second the data values keep swapping or something random happens the graph should reflect the changes. I have searched a lot but not found proper document or tutorial explaining this and I would highly appreciate it if someone can show me how to do this.
This is the FIDDLE I have created for work so far.
You can just use the method addData(), Example:
bar.addData([40, 60], "Google");
Working example - http://jsbin.com/kalilayohu/1/
this is the code
var canvas = document.getElementById('myChart');
var myBarChart = Chart.Bar(canvas,{
data:{
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}
]
},
options:{
scales: {
yAxes:[{
stacked:true,
gridLines: {
display:true,
color:"rgba(255,99,132,0.2)"
}
}],
xAxes:[{
gridLines: {
display:false
}
}]
}
}
});
You can update doing this:
myBarChart.data.datasets[0].data[4] = 50;//this update the value of may
myBarChart.update();

Categories