Add buffer to Y axis with chart js - chart.js

Sometimes chart value is the same height as chart height. For example im my picture red bar is 6, the same as y-axis top number. Can I add some buffer so chart bar never reaches top of y axis? Lets say y axis would go to 7 now (or similar).
Image show my problem (open image in new window for better view)

By Axis Range Settings
https://www.chartjs.org/docs/latest/axes/cartesian/linear.html#axis-range-settings
suggestedMax: 7
1/2. Static max value example
Change min to 10 and max to 90 (For data[30, 40, 50, 60]).
let chart = new Chart(ctx, {
type: 'line',
responsive: true,
data: {
datasets: [{
label: 'First dataset',
data: [30, 40, 50, 60]
}],
labels: ['January', 'February', 'March', 'April']
},
options: {
scales: {
yAxes: [{
ticks: {
suggestedMin: 10,
suggestedMax: 90
}
}]
}
}
});
<canvas id="ctx" width="800" height="350"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
2/2. Dynamic "buffer"
First no one solution for this idea (The max value related to your data structure). For the most basic data structure (Flat), this is one solution:
Get the max value of [20,40,60, 80] ==> 80
updateScaleDefaults Change max y-axis to max + buffer (20 in this example)
updateScaleDefaults - The default configuration for a scale can be easily changed using the
scale service. All you need to do is to pass in a partial
configuration that will be merged with the current scale default
configuration to form the new default. https://www.chartjs.org/docs/latest/axes/#updating-axis-defaults
Example:
For data: [20,40,60, 80]
/* data */
var data = {
labels: ["Africa", "Asia", "Europe", "America"],
datasets: [{
/* data */
label: "Population (millions)",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f", '#1d49b8'],
data: [20,40,60, 80]
}]
};
/* buffer trick */
var buffer = 20;
const dataSet = data.datasets[0].data;
console.log("data: " + dataSet);
/* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max */
var maxDATAvalue = Math.max(...dataSet);
var maxValuePlusBuffer = maxDATAvalue + buffer;
console.log("max value(" + maxDATAvalue + ") / Plus Buffer(" + maxValuePlusBuffer + ")");
/* The default configuration for a scale can be easily changed using the scale service. */
/* https://www.chartjs.org/docs/latest/axes/#updating-axis-defaults */
Chart.scaleService.updateScaleDefaults('linear', {
ticks: {
max: maxValuePlusBuffer
}
});
var options = {
responsive: true,
title: {
text: 'Set max value to max(data) + Buffer',
display: true
},
scales: {
xAxes: [{
stacked: true,
ticks: {
},
}],
yAxes: [{
stacked: true,
}]
}
};
var myChart = new Chart(document.getElementById("chart"), {
type: 'bar',
data: data,
options: options
});
<canvas id="chart" width="800" height="350"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
Related Stackoverflow Q:
How to set max and min value for Y axis
ChartJS: How to set fixed Y axis max and min

Related

Chart.js v3.x time series on x axis

so I'm basically pulling my hair as I can't get this to work for hours straight.
I'm trying to do a (I assumed simple) line-graph with on the x-axis time of day in hours and on the y-axis number of views. I'm trying to set the x-axis range as -24 hours until now.
My code is as follows. What am I doing wrong?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js"></script>
<div style="width: 500px; height: 500px;"><canvas id="myChart" width="400" height="400"></canvas></div>
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: '# of Votes',
data: [{x:'1619701200',y:41},{x:'1619704800',y:9},{x:'1619708400',y:21}]
}]
},
options: {
scales: {
x: {
type: 'time',
min: Date.now() - (24 * 60 * 60 * 1000),
max: Date.now()
}
}
}
});
</script>
EDIT: the problem is that the x-axis doesn't extend to 24 hours prior to now(). Also, there are 3 values in the dataset, but only two are shown. You can even edit the x-values to whatever you want and the entire graph stays the same.
EDIT2:
Could someone help me get this right? I've pasted my data below:
What I am trying to achieve:
X-axis going from now until 24 hours prior with an interval of 1 hour between ticks, formatted as 'd-m-Y H:00:00'. The data now is in seconds since epoch, if I need to change that please let me know!
Y-axis going from 0 to whatever the max is in the dataset
What CDNs do I have to include? I find the documentation on chart.js, moments, adapters etc quite unclear and everything I find on the internet is for prior versions.
Thank you!!
<div style="width: 500px; height: 500px;"><canvas id="myChart" width="400" height="400"></canvas></div>
<script>
new Chart(document.getElementById("myChart"), {
type: 'line',
data: {
labels: ['1619701200','1619704800','1619708400','1619715600','1619719200','1619722800','1619726400','1619730000','1619733600','1619737200','1619744400','1619773200','1619780400','1619784000','1619787600','1619791200','1619794800','1619798400','1619802000','1619809200','1619812800','1619816400','1619820000','1619823600','1619856000'],
datasets: [{
data: [41,9,21,80,277,151,68,88,82,48,12,1,97,36,81,21,63,49,44,15,10,44,81,4,9],
label: "Views",
borderColor: "#3e95cd",
fill: false
},
{
data: [1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,4,1,1],
label: "Visitors",
borderColor: "#3e95cd",
fill: false
}
]
}
</script>
We want you to keep your hair :-)
Try the following 2 Options for latest version of Chart.js
Chart.js v3.2.1 (not backwards compatible with v2.xx)
Option 1:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
// gets you the latest version of Chart.js, now at v3.2.1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script>
// You need moment.js and adapter for time or timeseries to work at x-Axis
<div style="width: 500px; height: 500px">
<canvas id="myChart" width="400" height="400"></canvas>
</div>
<script>
const startDate = new Date(1619701200*1000);
// first label from your data, times 1000 to get milliseconds,
// for last 24 hours from now, see further down below
const myLabels = [];
let nextHour = startDate;
let i = 0; // tip: declare i outside for-loop for better performance
for (i; i < 24; i++) {
nextHour = new Date((1619701200 + (i*3600)) *1000);
myLabels.push(nextHour);
};
const ctx = document.querySelector('canvas').getContext('2d');
const myChart3x = new Chart(ctx, {
type: 'line',
data: {
labels: myLabels,
datasets: [{
data: [41,9,21,80,277,151,68,88,82,48,12,1,97,36,81,21,63,49,44,15,10,44,81,4,9],
label: "Views",
borderColor: "#3e95cd",
fill: false
},
{
data: [1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,4,1,1],
label: "Visitors",
borderColor: "#3e95cd",
fill: false
}
]
},
options: {
scales: {
x: {
type: 'timeseries',
time: {
unit: 'hour', // <-- that does the trick here
displayFormats: {
hour: 'D-M-Y H:00:00'
},
tooltipFormat: 'D-M-Y H:00:00' // <-- same format for tooltip
}
},
y: {
min: 0
}
}
}
});
</script>
And this is what your chart would look like:
If you want to calculate dynamically the last 24 hours from now for your x-Axis, I would suggest to use moment.js instead:
<script>
// ...
const startDate = moment().subtract(1, 'd');
const myLabels = [];
let nextHour = startDate;
let i = 0;
for (i; i < 24; i++) {
nextHour = moment().add(i, 'h');
myLabels.push(nextHour);
};
// ....
</script>
Also, be aware that moment.js uses slightly different formatting string:
'D-M-Y H:00:00' instead of 'd-m-Y H:00:00'
Option 2:
If you have your data in json-format
data: [{x:1620237600000,y:41},{x:1620241200000,y:9},{x:1620244800000,y:21}]
like your first code snippet on top, using min and max at x-Axis: (Advantage: you don't have to define labels-array for x-Axis)
<script>
const ctx = document.querySelector("canvas").getContext("2d");
var myChart = new Chart(ctx, {
type: "line",
data: {
datasets: [{
label: "Views",
data: [{x:1620237600000,y:41},{x:1620241200000,y:9},{x:1620244800000,y:21}]
// x-value without quotes (has to be a number)
// and multiply by 1000 to get milliseconds
},
{
label: "Visitors",
data: [{x:1620237600000,y:1},{x:1620241200000,y:1},{x:1620244800000,y:2}]
}]
},
options: {
scales: {
x: {
type: "time", // <-- "time" instead of "timeseries"
min: Date.now() - (24 * 60 * 60 * 1000),
max: Date.now(),
time: {
unit: "hour", // <-- that does the trick here
displayFormats: {
hour: "D-M-Y H:00:00"
},
tooltipFormat: "D-M-Y H:00:00"// <-- same format for tooltip
}
},
y: {
min: 0,
max: 100
}
}
}
});
</script>
You should get the following:
I hope I understood correctly your need and hope this helps.
It needs more settings, I've searched and by trial/error - credit to this jsfiddle - , these are the results.
See updated working jsfiddle:
/*
Source: https://jsfiddle.net/microMerlin/3wfoL7jc/
*/
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: '# of Votes',
data: [{
x: '1619701200',
y: 41
}, {
x: '1619704800',
y: 9
}, {
x: '1619708400',
y: 21
}]
}]
},
options: {
responsive: true,
scales: {
xAxes: [{
min: Date.now() - (24 * 60 * 60 * 1000),
max: Date.now(),
type: "linear",
position: "bottom",
//stacked: true,
ticks: {
//beginAtZero: true,
userCallback: function(t, i) {
/*console.log("t: " + t.toString());
console.log("i: " + i.toString());*/
return i;
}
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="width: 500px; height: 500px;"><canvas id="myChart" width="400" height="400"></canvas></div>

Add space Between Columns in Bar chart. chartjs

I'm creating graphs using chart js V 2.9.3.
When I create the graph with a small amount of data it renders data perfectly but when the amount of data is increasing, the chart becomes Crowded.
A graph has two columns in single label.
I'm also not able to set the labels without rotation.
var config = {
type: 'bar',
data: {
labels: _datesForLabel,
datasets: _chartDataWithOptions,
},
options: {
tooltips: {
},
plugins: {
colorschemes: {
scheme: 'office.Waveform6'
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
}
}],
xAxes: [{
barThickness: 40,
maxBarThickness: 40,
barPercentage: 1.0,
categoryPercentage: 1.0,
ticks: {
min: 0,
},
}]
}
}
};
myBarChart = new Chart(ctx, config);
These are the options I used.
given is the screenshot of the output
output Image
can anyone help me with this.
thank you
Remove this barThickness: 40, (40 in pixels). In your case "No space/room" for such width = overlaps & broken layout.
https://www.chartjs.org/docs/latest/charts/bar.html#barthickness
Basic snippet (Base on your code) (change barThickness barPercentage barPercentage):
https://www.chartjs.org/docs/latest/charts/bar.html#barpercentage-vs-categorypercentage
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");
var _datesForLabel = ["2020-02-10",
"2020-02-13",
"2020-02-17",
"2020-02-18",
"2020-02-19",
"2020-02-20",
"2020-02-21",
"2020-02-22",
"2020-02-23",
"2020-02-24",
"2020-02-25",
"2020-02-26",
"2020-02-27",
"2020-02-28",
"2020-02-29",
"2020-03-01",
"2020-03-02",
"2020-03-03",
"2020-03-04",
"2020-03-05",
"2020-03-07",
"2020-03-08",
"2020-03-09",
"2020-03-10","2020-02-10",
"2020-02-13",
"2020-02-17",
"2020-02-18",
"2020-02-19",
"2020-02-20",
"2020-02-21",
"2020-02-22",
"2020-02-23",
"2020-02-24",
"2020-02-25",
"2020-02-26",
"2020-02-27",
"2020-02-28",
"2020-02-29",
"2020-03-01",
"2020-03-02",
"2020-03-03",
"2020-03-04",
"2020-03-05",
"2020-03-07",
"2020-03-08",
"2020-03-09",
"2020-03-10"]
var _chartDataWithOptions =[];
_chartDataWithOptions.push({
label:"dataseries1",
data:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24],
backgroundColor:"blue"
})
_chartDataWithOptions.push({
label:"dataseries2",
data:[2,3,4,5,6,7,8,9,10,12,13,11,10,19,14,12,11,18,26,23,21,28,24,2,3,4,6,9,1,2,1,11,12,13,14,15,16,17,18,19,20,21,22,23,11,22,4,6,3,6],
backgroundColor:"red"
})
var config = {
type: 'bar',
data: {
labels: _datesForLabel,
datasets: _chartDataWithOptions,
borderSkipped: 'top'
},
options: {
// responsive: true,
tooltips: {
// mode: ''
},
plugins: {
colorschemes: {
scheme: 'office.Waveform6'
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
}
}],
xAxes: [{
// barThickness: 40, // number (pixels) or 'flex'
maxBarThickness: 40,
barPercentage: 1,/* change this */
categoryPercentage: 0.5,/* change this */
ticks: {
min: 0,
},
}]
}
}
};
myBarChart = new Chart(ctx, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" ></script>
<div style="height: 500px; width: 100%;">
<canvas id="myChart" ></canvas>
</div>
About "set labels without rotation" - again "no room" - by maxRotation: 0, - full answer + example her: Chart Js Change Label orientation on x-Axis for Line Charts
"To much points/data" issue:
For now "no way" to auto group data - one idea is to use
stacked: true ("save room") - or manually filter your data (Show fewer points - related StackOverflow Q: Chartjs 2 scaling lots of data points).
Related Github feature request: https://github.com/chartjs/Chart.js/issues/4053

Chart.js display x axis labels ON ticks in bar chart, not between

I have this chart:
...which is displaying exactly how I want it to with one exception... The data in the bars is for between the two times in the x axis... so all the labels need shifting to lie on the grid lines, not between them as default for a bar chart. So the red and blue bar is data between 8:00 and 9:00. I hope I've explained that clearly enough.
I'm trawling through the Chart.js docs and it just doesn't seem like this is possible! I know I could change my labels to be, for example, 8pm - 9pm, but that seems a much more visually clunky way of doing it. Is there a way anyone know of achieving this? Ideally there would be another '12am' on the last vertical grid line too.
You can draw the tick lables at the desired position directly on to the canvas using the Plugin Core API. It offers number of hooks that may be used for performing custom code. In below code snippet, I use the afterDraw hook to draw my own labels on the xAxis.
const hours = ['00', '01', '02', '03', '04', '05', '06'];
const values = [0, 0, 0, 0, 10, 6, 0];
const chart = new Chart(document.getElementById('myChart'), {
type: 'bar',
plugins: [{
afterDraw: chart => {
var xAxis = chart.scales['x-axis-0'];
var tickDistance = xAxis.width / (xAxis.ticks.length - 1);
xAxis.ticks.forEach((value, index) => {
if (index > 0) {
var x = -tickDistance + tickDistance * 0.66 + tickDistance * index;
var y = chart.height - 10;
chart.ctx.save();
chart.ctx.fillText(value == '0am' ? '12am' : value, x, y);
chart.ctx.restore();
}
});
}
}],
data: {
labels: hours,
datasets: [{
label: 'Dataset 1',
data: values,
categoryPercentage: 0.99,
barPercentage: 0.99,
backgroundColor: 'blue'
}]
},
options: {
responsive: true,
legend: {
display: false
},
scales: {
xAxes: [{
type: 'time',
time: {
parser: 'HH',
unit: 'hour',
displayFormats: {
hour: 'Ha'
},
tooltipFormat: 'Ha'
},
gridLines: {
offsetGridLines: true
},
ticks: {
min: moment(hours[0], 'HH').subtract(1, 'hours'),
fontColor: 'white'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Format Y axis of Chart.JS as Time

I have this chart below, I want to scale the Y axis using the TIME (the time isn't time of day it is total hours,mins, seconds so could be over 24 hours) just can't seem to get it to work, all I get is a blank screen, sure it's a syntax error but can't spot it! Thanks
var ctx = document.getElementById("myChart3").getContext('2d');
var myChart3 = new Chart(ctx, {
type: 'line',
data: {
labels: ["2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017"],
datasets: [
{
label: "Time",
backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850", "#565452", "#321456", "#129864", "#326812", "#215984"],
data: ["11:46:07", "11:41:14", "11:55:26", "12:14:58", "11:54:55", "11:54:04", "12:28:29", "12:35:18"]
}
]
},
options: {
scales: {
yAxes: [{
type: 'time',
time: {
displayFormats: {
minutes: 'h:mm:ss a'
}
}
}]
}
}
});
Time scale works only for X axis.
It can only be placed on the X axis.
But for Y you can use a linear scale and express each time as date in milliseconds since 1970-01-01 (how the usual Date object does).
PLUNKER or use the following example:
$(function(){
const ctx = document.getElementById('myChart').getContext('2d');
let years = ["2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017"];
let times = ["11:46:07", "11:41:14", "11:55:26", "12:14:58", "11:54:55", "11:54:04", "12:28:29", "12:35:18"];
let data = years.map((year, index) => ({
x: moment(`${year}-01-01`),
y: moment(`1970-02-01 ${times[index]}`).valueOf()
}));
let bckColors = ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850", "#565452", "#321456", "#129864", "#326812", "#215984"];
let myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: "Time",
backgroundColor: 'rgba(188, 229, 214, 0.7)',
pointBackgroundColor: bckColors,
data: data,
pointBorderWidth: 2,
pointRadius: 5,
pointHoverRadius: 7
}
]
},
options: {
scales: {
xAxes: [
{
type: 'time',
position: 'bottom',
time: {
displayFormats: {
years: 'YYYY'
},
unit: 'year'
}
}
],
yAxes: [
{
type: 'linear',
position: 'left',
ticks: {
min: moment('1970-02-01 00:00:00').valueOf(),
max: moment('1970-02-01 23:59:59').valueOf(),
stepSize: 3.6e+6,
beginAtZero: false,
callback: value => {
let date = moment(value);
if(date.diff(moment('1970-02-01 23:59:59'), 'minutes') === 0) {
return null;
}
return date.format('h A');
}
}
}
]
}
}
});
});
<html>
<head>
<script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://npmcdn.com/moment#2.14.1"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
</head>
<body>
<canvas id="myChart" width="500" height="300"></canvas>
</body>
</html>
Explanation
You can have the years on X axis which can be a linear, time or category scale.
In this example X axis is a time scale.
The following code is used to generate values for X and Y axis:
let data = years.map((year, index) => ({
x: moment(`${year}-01-01`),
y: moment(`1970-02-01 ${times[index]}`).valueOf()
}));
For X axis I used moment js to create a date on the first day of the corresponding year.
For Y axis I used moment js to create the date in milliseconds since 1970-01-01. In this case all hours are combined with a day to form a date. 1970-02-01 in order to prevent an edge cases that may happen for 1970-01-01. Then these milliseconds, since 1970-01-01, are used with the Y axis linear scale.
Y axis tick.callback is used to format the corresponding milliseconds to an hour. Thus using the format h A to obtain for example 1 AM, 1 PM, 12 AM, 12 PM, ....

ChartJS linechart edit yAxis labels

Trying to get a linechart in ChartJS working according to the wishes of our clients, but I've run into an issue: When an entire week of data (we do sales) is 0, the labels plotted on the yAxis go below 0 -which is something our clients don't want. I've looked at scaleoverride, suggestedMin, and beginAtZero but none worked.
How can I change the labels so it will always have 0 as a minimum?
Complimentary image below, to visualise the issue:
The code (with one of the not-working methods I've tried):
var canvas = document.getElementById('salesChart').getContext('2d');
salesChart = new Chart(canvas, {
type: 'line',
scaleOverride: true,
scaleSteps: 10,
scaleStepWidth: 20,
scaleStartValue: 0,
data: {
labels: chartLabels,
datasets: [{
label: 'Sales',
data: chartData,
backgroundColor: "rgba(37,185,153,0.7)"
}],
},
options: {
maintainAspectRatio: false,
responsive: true
}
});
This worked for me:
options: {
maintainAspectRatio: false,
responsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
Note: I left the rest of the chart config as is. You did not explicitly supply the chartLabels and chartData variables, so I used:
var chartLabels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var chartData = [0, 0, 0, 0, 0, 0, 0];
Fiddle: https://jsfiddle.net/3c4yq5oq/