Charts.js Dynamic Ticks - javascript

I am using Charts.js and using it to display data over different periods of time, the time periods are based on a user input. I am displaying date labels on the x-axis but sometimes these can range over a period of 0-12 months. I want to dynamically alter this so that if the date range is over 2 months then the labels would show per month? Also the data within that range would be grouped per month. Like when using Google Analytics.
The below is the Javascript I am using to generate the graphs.
<script>
var ctx = document.getElementById('directtraffic').getContext('2d');
var directtraffic = new Chart(ctx, {
type: 'line',
data: {
labels: ["2017-05-01","2017-05-02","2017-05-03","2017-05-04","2017-05-05","2017-05-06","2017-05-07","2017-05-08","2017-05-09","2017-05-10","2017-05-11","2017-05-12","2017-05-13","2017-05-14","2017-05-15","2017-05-16","2017-05-17","2017-05-18","2017-05-19","2017-05-20","2017-05-21","2017-05-22","2017-05-23","2017-05-24","2017-05-25","2017-05-26","2017-05-27","2017-05-28","2017-05-29","2017-05-30","2017-05-31"],
datasets: [{
label: 'Sessions (01/05/2017 - 31/05/2017)',
data: ["169","278","287","223","252","129","97","246","266","285","262","203","107","121","319","261","336","291","227","110","94","237","263","259","239","172","79","77","111","257","233"],
responsive: true,
tooltips: {
mode: 'index',
intersect: false,
},
legend: {
display: false,
},
hover: {
mode: 'nearest',
intersect: true
},
backgroundColor: '#5cbae6',
borderColor: '#5cbae6',
fill: false
},{
label: 'Sessions (01/04/2017 - 30/04/2017)',
data: ["103","100","261","280","258","250","197","70","94","248","206","239","198","113","113","108","99","248","245","250","225","107","86","244","245","268","299","223","98","119"],
responsive: true,
tooltips: {
mode: 'index',
intersect: false,
},
legend: {
display: false,
},
hover: {
mode: 'nearest',
intersect: true
},
backgroundColor: '#b6d957',
borderColor: '#b6d957',
fill: false
}]
},
options: {
animation: false,
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
gridLines: {
display:false
}
}]
}
}
});
</script>

If I understand your question correctly, you will need to add ticks under scales and in you case xAxes. In ticks you can specify the step size. The step size is how much it increments each time. In the step size you can make a call to a function that determines the step size you need. So you could make a function called calcualteStepSize and pass in the dates if it is over over 2 months then return a step size of 1. Below is just some pseudocode
ticks: {
stepSize: calcualteStepSize(data)
}
function calcualteStepSize(data) {
if data range is greater than 2 months
return 1
else return some other calculation
}

Related

Chartjs-plugin-zoom plugin does not change x axis labels

I am working with the chart.js module in order to plot some data and am using the chartjs-plugin-zoom in order to enable zooming and panning however although the zooming works the labels on the x axis will not change for whatever reason.
I have seen similar questions but they all dealt with time series data and therefore the advice was unhelpful.
Here is the plot zoomed out:
and here is it zoomed in:
The key thing to notice is how the labels on the y axis have changed but the x axis labels have not changed. Here is the relevant config variable of the chart:
const config3 = {
type: 'line',
data: {
labels: [I ran out of chars but this is just a very long list of numbers in this format: 1,2,3,4,5],
datasets: [
{
label: "",
backgroundColor: '#'+Math.floor(Math.random()*16777215).toString(16),
borderColor: '#0071BC',
data: [I ran out of chars but this is just a very long list of numbers in this format: 1,2,3,4,5],
fill: false,
borderWidth: 1,
},
],
},
options: {
responsive: true,
title: {
display: true,
text: 'Peak: -1.2188'
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Frequency (Hz)'
},
ticks:{
autoSkip: true,
maxTicksLimit: 20
},
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Amplitude'
}
}],
},
plugins:{
zoom: {
pan: {
enabled: true,
mode: 'xy',
speed: 20,
threshold: 10,
},
zoom: {
enabled: true,
drag: false,
mode: "xy",
speed: 0.1,
// sensitivity: 0.1,
}
}
},
elements: {
point:{
radius: 0
}
}
}
};
If needed I can provide more code but I imagine the mistake is probably contained in the config. I tried changing zoom.mode to be 'x' but that did not work.
In case someone else comes along this I figured out a solution that is pretty unintuitive.
The first problem is the way that labels are dealt with in chart.js and because they are treated as categories not x data the way that I thought they were. Therfore first you must pass your data in as coordinates in this format:
(as shown in this documentation: https://www.chartjs.org/docs/latest/charts/line.html)
data: [{
x: 10,
y: 20
}, {
x: 15,
y: 10
}]
And delete the labels variable.
However this will not work with line charts despite what the documentation says. To get around this you can set: type: 'scatter' and inside the dataset write showLine: true
This will generate a line plot where the x labels are auto generated and zooming will work perfectly.
I also think there was a performance boost which is a nice bonus.

ChartJS - How to increase the maximum degree of label rotation on x-axis?

I have a line chart, and at first, all the labels on x-axis are fully horizontal. Something like this:
Now if add more data, the labels start to rotate:
Until comes a point where it seems to have reached the maximum degree to which it can rotate:
By the looks of it, I think the maximum degree is 45. So now, if I add a little more data, instead of rotating the labels more, it removes every one in two labels, and becomes like this:
How can I increase this degree to 90, so that the labels rotate as much as becoming fully vertical?
Here's the code I used for the chart:
new Chart(chart, {
type: 'line',
data: chart_data,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
position: 'top',
labels: {
boxWidth: 5,
usePointStyle: true
}
},
events: ['click', 'mousemove'],
onClick: clicked,
pan: {
enabled: true,
mode: 'x',
onPanComplete: function(event) {
console.log(event)
}
},
zoom: {
enabled: true,
mode: 'x'
}
}
});
You can configure this using the maxRotation property of the common tick configuration object.
Your code needs to be modified like so:
options: {
scales: {
xAxes: [{
ticks: {
maxRotation: 90
}
}],
yAxes: [{
...
The keyword of the issue is not rotation i think, it is Tick on xAxes.
I think this link can help you :
https://www.chartjs.org/docs/latest/axes/styling.html#tick-configuration
also
Chart.js: evenly distribute ticks when using maxTicksLimit
xAxes: [{
ticks: {
autoSkip: false, // Skip or not?
maxTicksLimit: 30 // How much?
}
}]
and rotation just can help as #timclutton said here : https://stackoverflow.com/a/58275468/7514010

Chart data isnt showing in the canvas but console.log shows the expected values

So its my first time using chartjs. Im trying to use stacked horizontal charts. I have 2 values which I calculate using some sort function. I do console.logs to check if values are correct and they are both as expected. But when i try to update the chart only the first value shows in the canvas, and the 2nd value shows 0 but my chart gridlines adjusts correctly. Im not too sure what is happening.
Here is where I declare my chart data
var eventDays1 = 0;
var eventDays2 = 0;
var barChartData = {
labels: ['Events'],
datasets: [{
label: eventName1,
backgroundColor: "#E5C1BD",
data:[eventDays1]
}, {
label: eventName2,
backgroundColor: "#D2D0BA",
data:[eventDays2]
}
]};
Here is the actual chart
myBarChart = new Chart(ctx, {
type: 'horizontalBar',
data: barChartData,
options: {
legend: {
display: true,
labels: {
fontColor: 'black',
fontSize:20,
}
},
responsive: true,
scales: {
xAxes: [{ stacked: false,
ticks:{
fontColor:"black"
},
scaleLabel: {
display: true,
labelString: 'Days',
fontColor:"black"
}
}],
yAxes: [{
ticks: {
beginAtZero:true,
max:365,
fontColor:"black"
},
stacked: true,
}]
}
},
});
Here is my updateChart function that I call. Note that the console.logs
are values that I expect already.
function updateChart(newList){
eventDays1 = newList[0];
if(newList.length == 2){
eventDays2 = newList[1];
}
myBarChart.data.datasets[0].data[0] = eventDays1;
myBarChart.data.datasets[0].data[1] = eventDays2;
console.log("data 1 "+eventDays1);
console.log("data 2 "+eventDays2);
myBarChart.update();
}

Chart.js mixed chart : Lines not starting at zero

current situation
chart
what i want : chart
I build a mixed chart with lines and bars. I have problem with lines.
Lines not starting at zero.
Here is my codes;
https://jsfiddle.net/ameydan/vb4fsyqp/31/
` options: {
legend: {
display: false,
position: 'top',
},
elements: {
point: {
radius: 0
}
},
scales: {
yAxes: [{
stacked: true,
ticks: {
beginAtZero: true
}
}
],
xAxes: [{
stacked: true,
ticks: {
beginAtZero: true
}
}
]
}
}`
thanks in advance.
beginAtZero : true , not solved problem.
That is cause you setted stacked to true.
scales: {
yAxes: [{
stacked: **false**,
ticks: {
beginAtZero: true
}
}
],
xAxes: [{
stacked: true,
ticks: {
beginAtZero: true
}
}
]
}
EDIT:
Second thought coming from => https://www.chartjs.org/docs/latest/charts/mixed.html
At this point we have a chart rendering how we'd like. It's important to note that the default options for a line chart are not merged in this case. Only the options for the default type are merged in. In this case, that means that the default options for a bar chart are merged because that is the type specified by the type field.
I found a solution!
Just add this :
myChart.options.scales.xAxes[0].offset = false;
myChart.update();
The only counterpart is that if there's data # index 0 of a bar dataset, it will be only half drawn and the last one as well as shown here : https://jsfiddle.net/0qsh8znu/1/
I had the same issue. When I followed #rOulito 's solution, I found that the lack of offset for my line graph made it no longer line up with the data points of my bar graph, so that didn't work, sadly.
My solution was to follow the docs for a chartjs plugin for annotations
This is how I drew a line from the first data point of my line graph to the bottom left of the graph:
let options = {
plugins: {
annotation: {
annotations: {
line1: {
type: 'line',
yMax: 50000,
xMax: 0,
borderColor: 'black',
borderWidth: 3,
},
},
},
},
};

Remove top horizontal line in a horizontal bar chart (Chart.js 2)

I created a horizontal grouped bar chart in Chart.js but am getting stuck on a weird problem.
The problem is that while I disabled all grid lines and borders the chart is still showing a top horizontal line which I would like to get rid off.
It is visible in this screenshot: http://imgur.com/41YGxA8.
I also made a JSFiddle: https://jsfiddle.net/bsocw1v9/
function create_horizontal_bar_chart(){
/**
* Draw the chart on the correct canvas. Add the correct data sets
* and set the correct draw type.
*/
let ctx = document.getElementById('monthly_subscription_revenue_chart').getContext("2d");
let data = {
labels: ['Diensten'],
datasets: [
{
type: 'horizontalBar',
backgroundColor: "rgb(0,33,86)",
data: [2250],
stack: 1
},
{
type: 'horizontalBar',
backgroundColor: "rgb(219,219,219)",
data: [3000],
stack: 2
},
{
type: 'horizontalBar',
backgroundColor: "rgb(240,95,0)",
data: [750],
stack: 3
},
]
};
new Chart(ctx, {
type: 'horizontalBar',
data: data,
showScale: false,
options: {
legend: {
display: false
},
tooltips: {
enabled: false
},
hover: {
mode: null
},
scales: {
xAxes: [{
stacked: true,
display: false,
gridLines: {
drawBorder: false,
},
}],
yAxes: [{
stacked: true,
barPercentage: 0.9,
gridLines: {
drawBorder: false,
},
}]
}
}
});
}
I hope someone could help me with this problem as I simply can't figure out whats causing this.
You have only disabled borders on the edge of the chart (by setting drawBorder to false), not grid lines. The line that bugs you is a grid line. To disable grid lines for an axis use:
gridLines: {
display: false
}
Look at the docs under "Grid Line Configuration".

Categories

Resources