Chartjs show seconds on the x axis and volume on the y - chart.js

I would like to show y as time and x and volume of something
I basically if it takes 8.5 secs to do say 10 000 volume or 1000 000
I would like to have time on the x axis and volume on the y axis.
Time is not relative to a date, its time as in ticks, so its 0 start.
struggling to find a gd example to work from,
I have done quick POC's but seems like there should be and easier example to base my work from.
aka i believe i need to do some calculation to get the ranges, but even if i had the ranges unsure which chart type and setting would be best fit.
I want to display labels to the bottom displaying time in ms/s
[0,100,200,400, 800, 10000, 15000] ms - could then try some formatting options for divide by 1000 for secs.
strarted https://jsfiddle.net/co43r6ef/ but again seems like wrong direction.
also toying with but also seems iffy also wrong direction, is anyone else able to point me to an example... i can leverage.
to clarify it should start at 0 and move forward in time along x to the peek.
So when looking at the chart u can look at the peek and under it with a line going down it should be the time taken.
// var labels = []
// var tickms = 325362132 / 10000;
// for (let i = 0; i < tickms ; i++) {
// if (i%1000 === 0) {
// labels.push(i)
// }
// }
var ctx = $("#canvas")[0].getContext("2d");
var data = {
datasets: [
{
label: "Scatter Dataset",
// labels: labels,
data: [
{ x: 0, y: 0},
{ x: 10, y: 1000 },
{ x: 20, y: 2000 },
{ x: 30, y: 3000 },
{ x: 40, y: 6000 },
{ x: 50, y: 8000 },
{ x: 1066, y: 10000 }
]
}
]
};
var myLineChart = new Chart(ctx, {
type: "line",
data: data,
options: {
scales: {
xAxes: [
{
scaleLabel: {
display: true
},
}
]
}
}
});

You should be fine when you add
options: {
scales: {
xAxes: [{
type: 'linear'
}]
}
}
Here's an example: https://jsfiddle.net/1sxrtcw5/1/

Related

ApexCharts skipping X axis ticks

I would like to present a bar chart using Apex Charts.
The graphs shows some items, the more items the longer you can do some stuff. The items are presented in the Y axis. The X axis should represent months in a year, therefore I want it to be fixed between 0 and 12.
With the following options, it skips some numbers in the x axis:
var options = {
series: [{ data: [3,4,6,7,8.5] }],
chart: { type: 'bar', height: 250 },
plotOptions: {
bar: { borderRadius: 4, horizontal: true }
},
dataLabels: { enabled: false },
xaxis: {
categories: [2,3,5,6,7],
min: 0,
max: 12,
},
yaxis: {
labels: { formatter: function (val) { return val + ' items'; } },
},
title: {
text: 'Chart title', floating: true, align: 'center',
style: { color: '#444' }
}
};
If I omit the min/max in the xaxis, it works fine but the 12 months are not fixed as required.
In the example the 9 is skipped, but the actual bars are scalled correctly
I am loading the library using de direct script include:
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
Here you can find the official example/docs: https://apexcharts.com/javascript-chart-demos/bar-charts/basic/
Have I overlooked something? Or is it a bug?
Setting tickAmount to 12 seems to fix the problem, but I does not behave correctly with other numbers. (if I use 13 then it inserts two 6 tiks instead of inserting decimals)

Stacking area line charts with different x-values in data

We use the chart-js-react to build area charts in our service. Our chart will display logs information which is time-based data like, {x:"2022-06-27T21:00:00Z", y:25}.
Since the time could be a random value in each data point, so there are some issue when we want to display a few series with different X-values(different time), as shown in the image. We got overlapping and blank area when the X-value(timestamp) is missing in another series.
Update: checked this Issue: https://github.com/chartjs/Chart.js/issues/7695. I notice they did have some missing/ different X-value. but looks the x-value is not random. when I made the x-values mis-match. same issue: https://codepen.io/derrickwanglf/pen/RwMRMXM
TO Simply demonstrate our issue, I mock some data(real number as x-value) here.
https://codepen.io/derrickwanglf/pen/gOeMvEL
Do you know how can we stack the area chart even the x-values are random?
d0 = [{x:1, y:1}, {x:2, y:11},{x:3, y:1},{x:4, y:11},{x:5, y:10}, {x:6, y:8},{x:7, y:15},{x:8, y:2}]
d1= [{x:1, y:1}, {x:2, y:5}, {x:4, y:1}, {x:5, y:3}, {x:5.5, y:4},{x:7, y:5},{x:8, y:3}]
const ctx = document.getElementById("chart").getContext("2d");
const chart = new Chart(ctx, {
type: "line",
data: {
datasets: [
{
backgroundColor: "rgba(50,200,50,0.6)",
borderColor: "rgba(50,200,50,0.6)",
data: d0,
fill: "stack"
},
{
backgroundColor: "rgba(200,50,50,0.6)",
borderColor: "rgba(200,50,50,0.6)",
data: d1,
fill: "stack"
}
]
},
options: {
scales: {
x: {
type: "linear"
},
y: {
stacked: true,
}
},
elements: {
line: {
tension: 0.2
},
point: {
radius: 0
}
},
tooltips: {
mode: "nearest",
intersect: false,
axis: "x"
},
hover: {
mode: "nearest",
intersect: false,
axis: "x"
}
}
});

Chart.JS 2 automatic horizontal scroll upon changes on xAxis range not working anymore on Chart.JS 3?

I previously had a scatter graph in Chart.js 2 with the zoom plugin, in which I just had to add data and change the xAxis ticks' min/max to see a nice animated horizontal scroll from my old xAxis range to my new xAxis range.
For some reason I now use Chart.js 3.24 and the zoom plugin 1.1.1. Now the same graph with nearly the same options became quite ugly when animated:
newly added points e.g. at position (X,Y) have an animation going from (X,0) to (X,Y), instead of appearing directly at (X,Y).
when a point from a dataset is at the same position than a line from another dataset, they move at a different speed.
if many points and line are added, sometimes the lines are only shown after the "scrolling animation" ended.
sometimes a point appear at its correct final position before the "scrolling animation" even started.
The only solution I found was to disable animation when updating my graph, then use window.requestAnimationFrame to manually pan the graph myself with the zoom plugin.
Are you aware of a better/simpler recommended way to achieve this ?
Thanks in advance,
My old Chart.js options:
let zoom_options = {
pan: {
enabled: true,
mode: 'x',
rangeMin: { x: 0, y: null},
rangeMax: { x: null, y: null}
},
zoom: {
enabled: true,
drag: false,
mode: 'x',
rangeMin: { x: 0, y: null },
rangeMax: { x: null, y: null },
speed: 0.1
}
};
var ctx = graph.getContext('2d');
this._chartjs = new Chart(ctx, {
type: 'scatter',
data: {
datasets: []
},
options: {
legend: {
//display: false
},
scales: {
xAxes: [{
type: 'linear',
position: 'bottom',
}]
},
plugins: {
zoom: zoom_options // https://github.com/chartjs/chartjs-plugin-zoom
}
}
});
My old line options :
{
label: name,
showLine: false,
fill:false,
spanGaps: false, // I have some NaN values in my datasets.
backgroundColor: color.points_borders,
borderColor: color.line,
borderWidth:5,
pointRadius:5,
pointBorderWidth:2,
pointBorderColor: color.points_borders,
pointBackgroundColor: color.points,
data: []
}
My old update function:
this._chartjs.options.scales.xAxes[0].ticks.min = min;
this._chartjs.options.scales.xAxes[0].ticks.max = length;
this._chartjs.update();

Chart.js xaxis formatter changes the value shown in the chart

I'm creating a simple visualization that shows the evolution of the Temperature in the past 24h. It is shown in the picture.
In the x axis I'm showing the hours and I'm trying to format them so that 10 -> 10:00, and so on.
However, when I include the ticks.callback in the options, the chat shows as follows: it always starts at 0:00 while the correct chat, at this particular time starts at 12.
ticks: {
callback: function(value, index, ticks) {
return `${value}:00`;
}
}
As you can see I've been able to format the y axis, but there is something different with the x axis.
This is the whole configuration of the chart, in case the error is there:
const labels = this.extractLabels(this.props.data);
const dataPoints = this.extractData(this.props.data);
const data = {
labels: labels,
datasets: [{
label: 'Avg. Temperature',
data: dataPoints,
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
};
const options = {
scales: {
y: {
beginAtZero: true,
grace: '5%',
title: {
display: true,
text: 'Temperature',
font: {
size: 16
}
},
ticks: {
callback: function(value, index, ticks) {
return value + ' ÂșC';
}
}
},
x: {
title: {
display: true,
text: 'Date',
font: {
size: 16
}
},
ticks: {
callback: function(value, index, ticks) {
return `${value}:00`;
}
}
}
}
};
const config = {
type: 'line',
data: data,
options: options,
};
this.temperatureChart = new Chart(this.chartRef.current, config);
As per the tip in the docs:
The category axis, which is the default x-axis for line and bar charts, uses the index as internal data format. For accessing the label, use this.getLabelForValue(value). API: getLabelForValue
so to get the right display value your callback needs to be this:
ticks: {
callback: function(value, index, ticks) {
return `${this.getLabelForValue(value)}:00`;
}
}
You can edit the labels, but in my opinion a better solution would be to implement a Time cartesian axis. This would allow you to add more data without making changes to the labels. You would need to include a time adapter to make it work.
config:
const config = {
type: 'line',
data: data,
options: {
scales: {
xAxis: {
type: 'time',
ticks: {
source: 'labels', // get ticks from given labels
},
time: {
minUnit: 'minute', // smallest time format
displayFormats: {
minute: "HH:mm",
hour: "dd/MM HH:mm",
day: "dd/MM",
week: "dd/MM",
month: "MMMM yyyy",
quarter: 'MMMM yyyy',
year: "yyyy",
}
}
},
},
}
};
Here is a fiddle to show you how this would look: JSFiddle

Chartjs linechart with only one point - how to center

I have a chartjs linechart diagram to show the sales of different products on a range of dates. The user can select a date range (for example from 2015-12-01 to 2015-12-10) to view the sales per day and thats fine and its working.
But if the user selects only one day (range from for example 2015-12-01 to 2015-12-01), he gets the correct diagram, but it doesn't look good:
As you can see, the points are stick to the y-axis. Is there a possibility, to center the points on the diagram?
Thats how it should look like:
Instead of hardcoding the labels and values with blank parameters, use the offset property.
const options = {
scales: {
x: {
offset: true
}
}
}
Documentation: https://www.chartjs.org/docs/latest/axes/cartesian/linear.html#common-options-to-all-cartesian-axes
You can check the length of your labels (or data) arrays and add dummy non-renderable points to the left and right by using empty string labels and null value, like so
var chartData = {
labels: ['', "A", ''],
datasets: [
{
fillColor: "rgba(255, 52, 21, 0.2)",
pointColor: "#da3e2f",
strokeColor: "#da3e2f",
data: [null, 20, null]
},
{
fillColor: "rgba(52, 21, 255, 0.2)",
strokeColor: "#1C57A8",
pointColor: "#1C57A8",
data: [null, 30, null]
},
]
}
Fiddle - https://jsfiddle.net/pf24vg16/
Wanted to add to the above answer and say that I got a similar effect on a time series scatter plot using this:
if (values.length === 1) {
const arrCopy = Object.assign({}, values);
values.unshift({x: arrCopy[0].x - 86400000, y: null});
values.push({x: arrCopy[0].x + 2 * 86400000, y: null});
}
That only handles for a single point, however. To add in functionality for multiple points, I did the following:
const whether = (array) => {
const len = array.length;
let isSame = false;
for (let i = 1; i < len; i++) {
if (array[0].x - array[i].x >= 43200000) {
isSame = false;
break;
} else {
isSame = true;
}
}
return isSame;
}
if (values.length === 1 || whether(arr[0])) {
const arrCopy = Object.assign({}, values);
values.unshift({x: arrCopy[0].x - 86400000, y: null});
values.push({x: arrCopy[0].x + 2 * 86400000, y: null});
}
You might notice I'm just subtracting/adding a day in milliseconds into the x values. To be honest, I was just having the worst of times with moment.js and gave up haha. Hope this helps someone else!
Note: my code has a tolerance of 43200000, or 12 hours, on the time. You could use moment.js to compare days if you have better luck with it than I did tonight :)
For your specific problem, try to modify the options->scales->xAxes option like so:
options: {
title: {
display: true,
text: 'mytitle1'
},
scales: {
xAxes: [{
type: 'linear',
ticks: {
suggestedMin: 0,
suggestedMax: (11.12*2),
stepSize: 1 //interval between ticks
}
}],
More info at: Chart JS: Ignoring x values and putting point data on first available labels