Chartjs plugin annotation timestamp - javascript

I am using Chart.Js "2.8.0" and chartjs-plugin-annotation "0.5.7" to display boxes based on timestamp intervals
I am trying to show something like this:
based on timstamp intervals, but cannot find something from their docs.
The result is...:
code examples:
annotations.push({
type: 'box',
id: `status-${index}`,
xScaleID: `x-axis-${index}`,
yScaleID: `y-axis-${index}`,
backgroundColor: 'rgba(188, 170, 164, 0.2)',
borderWidth: 0,
xMin: data.linkedTime, // timestamp
xMax: data.unlinkedTime, // timestamp - can be null(till present)
label: {
enabled: true,
fontSize: 12,
drawTime: 'afterDraw',
content: data.name,
xAdjust: 0,
yAdjust: 0,
position: 'top'
}
});
chart xaxis (using dayjs let labels = items.map(({ time }) => this.$dayjs.unix(time));):
xAxes: [
{
type: 'time',
time: {
unit: 'day',
unitStepSize: 1,
displayFormats: {
day: 'MMM DD'
}
}
}
],
My guess is that i should format the xMin/xMAx values accordingly to xaxis (daysjs stuff), tried something('Oct 31' or this.$dayjs.unix(timestamp)) but it doesn't work... i guess i am missing something

Chart.js uses timestamps defined as milliseconds since the epoch. Source
Use .valueOf() to get timestamp in milliseconds from dayjs. Source
xMin: dayjs(...).valueOf(),
xMax: dayjs(...).valueOf(),

Related

Remove duplicate values from x-axis morris charts

I have to render series data for current month/quarter/year data using morris.js charts. The series has data points on daily basis and I see a repeating days on the x-axis.
jsfiddle
I also tried turning off parseTime and using xLabelFormat as suggested on few posts on SO using the code below but output has duplicate values for days:
Morris.Line({
element: element,
data: [
{"day":"2017-10-01 11:40:09","uniqueUsers":"180","sessions":"213"},
{"day":"2017-10-01 12:40:09","uniqueUsers":"217","sessions":"213"},
{"day":"2017-10-02 11:40:09","uniqueUsers":"539","sessions":"635"},
{"day":"2017-10-03 11:40:09","uniqueUsers":"684","sessions":"826"},
{"day":"2017-10-04 07:40:09","uniqueUsers":"1095","sessions":"1229"},
{"day":"2017-10-04 10:40:09","uniqueUsers":"822","sessions":"987"},
{"day":"2017-10-04 11:40:09","uniqueUsers":"568","sessions":"836"},
{"day":"2017-10-05 11:40:09","uniqueUsers":"335","sessions":"385"}
],
xkey: 'day',
xlabels: 'day',
xLabelFormat: function (x) {
var d = new Date(x.label.slice(0, 10) + "T" + x.label.slice(11, x.label.length));
return d.getDate() + ' ' + months[d.getMonth()];
},
ykeys: ['uniqueUsers', 'sessions'],
labels: ['Unique users', 'User sessions'],
pointSize: 2,
hideHover: 'auto',
lineColors: ['rgb(156, 39, 176)', 'rgb(121, 85, 72)', 'rgb(0, 188, 212)', 'rgb(255, 152, 0)'],
xLabelAngle: 50,
//dateFormat: function (d) {
// var ds = new Date(d);
// return ds.getDate() + ' ' + months[ds.getMonth()];
//},
behaveLikeLine: true,
parseTime: false
});
How can I remove duplicate values on x-axis?
these are not redundant values, these are dates formatted automatically by Morris.js.
Therefore, you have 2 choices:
either do not parse the dates, and just display the value of "day", by setting parseTime to false
or you change date format on x-axis, by setting xLabels to hour
You can read more about these settings in the documentation.

Highcharts - cannot force x axis to stop on a certain date

I am using highcharts/highstock and I send some data to the client.
I tried various sets of settings, but I cannot force x axis to stop on a certain date.
For example, I create a chart that has data from 20/3/2019 to 25/3/2019. The interval must always be 5 minutes.
The starting point is correct, it starts in 20/3/2019.
But the last point is always a day more. Its about 35 more points of 26/3/2019, instead of stopping at 25/3/2019.
*if this changes anything, the starting point should be 20/3/2019 00:00 , but it actually starts at 20/3/2019 03:00 in highcharts.
My data are
{
time:{
useUTC:false
},
boost: {
enabled: true,
allowForce:true,
usePreallocated:true,
useGPUTranslations: true
},
chart: {
type: "line",
zoomType: 'x'
},
title: {
text: item.title
},
xAxis: {
type: 'datetime',
tickInterval: 5 * 60 * 1000 , /*5 min */
max: pointStop,
labels: {
format:'{value:%H:%M:%S}'
},
dateTimeLabelFormats: {
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%b. %e',
week: '%b. %e',
month: '%b. %y',
year: '%Y'
}
},
yAxis: {
title: {
text: item.title
},
alignTicks:'left',
textAlign:'left',
align:'middle',
opposite:false
},
series: [
{
boostThreshold: 150,
name: item.title,
pointStart: pointStart,
pointInterval: 5 * 60 * 1000,
data: item.array,
dataGrouping:{
approximation: 'average',
enabled:true,
forced:true,
groupAll:true,
groupPixelWidth:20
}
}
]
}
What am I doing wrong?
Thanks
It sounds like an issue setting the tick count. The documentation states
If a tickAmount is set, the axis may be extended beyond the set max in order to reach the given number of ticks. The same may happen in a chart with multiple axes, determined by chart. alignTicks, where a tickAmount is applied internally.
You need to disable oridinal option, which is enabled by default in Highstock:
xAxis: {
ordinal: false,
...
}
Live demo: http://jsfiddle.net/BlackLabel/6rqcLhp0/
API Reference: https://api.highcharts.com/highstock/xAxis.ordinal

Create ticks at certain time positions on a chartjs cartesian time axis

I created a realtime chart that updates about every 10 seconds by adding a new value and removing an old one.
I'm a bit unhappy about the chosen ticks of the time axis. Every 10 Minutes is fine, but I'd prefer values like 15:50,16:00,16:10. I looked around the documentation time axis but did not find anything promising.
My definition of my xAxes looks like:
xAxes: [
{
gridLines: {
display: true
},
type: "time",
time: {
unit: "minute",
unitStepSize: 10,
displayFormats: {
minute: "HH:mm"
}
},
ticks: {
min: 0,
max: this.datapoints.length,
autoSkip: true,
maxTicksLimit: 10
}
}
]
I tried to loop over the dataset and find the 'first pretty time' object and set this object as my ticks.min object. But this did not work.
OK I found it. The property is in the time attribute:
time: {
unit: "minute",
unitStepSize: 10,
displayFormats: {
minute: "HH:mm"
},
min: firstprettyTime, // <- moment js object
},
All praise to this guy's answer.

How to make yAxis start from a specific time with bar series in highchart?

I want to have bar chart start from a specific time (1.Apr)
So I implemented this in below sample:
(jsFiddle) sample with axis right but can the bar disappear
With the code below
yAxis: {
type: 'datetime',
min:Date.UTC(2010, 3, 1)
},
yAxis actually start from 1.Apr, but I can not see the bar itself .
If I remark the min line as below
yAxis: {
type: 'datetime'
//min:Date.UTC(2010, 3, 1)
},
Now I can see the bar appear, but the yAxis default show from 1.Jan.
Can anyone help me make the bar visible and yAxis starting from 1.Apr ?
I think I found what you're searching.
There's an option in yAxis called min, it's used to set the lowest value of your axis. Like that :
yAxis: {
type: 'datetime',
min: Date.UTC(2010, 3, 1)
}
Hope it's what you're searching. Chears from a bear.
Let me explain how datetime axis works. In general, datetime axis is based on number of milliseconds since 1970-01-01 00:00:00. That means, setting y: 3600 * 1000 will render column from 1970-01-01 00:00:00 to 1970-01-01 01:00:00. You want to start chart as 1st of April, but your data doesn't reflect that. In other words, you need provide such info, for example:
series: [{
name: 'UP',
color: 'lime',
data: [{
x: 1,
y: Date.UTC(2015, 5, 1, 1, 0, 0) // 2015-06-01 01:00:00
// or:
// y: 1433120400000
// is the same as above use for Date.UTC()
}]
}]
Live demo: http://jsfiddle.net/v9582phy/4/
Thanks for your replying, it helps. And I had extended the code yours with further enhancement as below
yAxis: {
type: 'datetime',
labels: {
formatter: function () {
var x=new Date(Date.UTC(2015, 3, 1)+this.value*1000*60)
return moment(x).format('MMM/DD HH:mm:ss')
}
}
},
with series data as
series: [{
data: [{
status:'studying',
color: 'lime',
x: 1,
y: 5
}, {
status:'playing guitar',
color: 'yellow',
x: 2,
y: 10
}, {
status:'exam',
color: 'red',
x: 2,
y: 23
}]
}]
And I got stacked bar which each bar present how many minutes for lasting status
Live demo: http://jsfiddle.net/v9582phy/11/

Flot Date Issue

i'm trying to display a date field in flot:
Data:
var data = [
[parseInt(1309150800.0)*1000, 220],
[parseInt(1309064400.0)*1000, 230],
];
Flot creation:
$.plot($("#graph"), [ data ], {
grid: {
hoverable: true
},
xaxis: {
mode: "time",
timeformat: "%d.%m.%y"
},
yaxis: {
mode: "number",
tickSize: 2
},
series: {
lines: { show: true },
points: { show: true }
}
});
According to this site http://tools.semsym.com/index.php?tool=timestamp&timestamp=1309150800 the timestamp is Jun 26, 2011 10:00:00 PM.
But the graph looks like: http://i.stack.imgur.com/NUayx.png
The dots are a bit off. The first one should be at 26, but is at 25,5. I played a bit with timestamp formatting but wasn't able to get it to the specific point.
What am i missing?
Also it shows "26.06.2011" about 6 times. What config is needed to keep it at 1?
Make sure you set a minTickSize. Here is an example at http://jsfiddle.net/hAXHq/ where I have set minTickSize to 1 day and set the min/max values explicitly. You should be able to set your own min/max programmatically depending on your data.
Here is the code:
var data = [
[parseInt(1309150800.0)*1000, 220],
[parseInt(1309064400.0)*1000, 230]
];
$.plot($("#placeholder"), [ data ], {
grid: {
hoverable: true
},
xaxis: {
mode: "time",
timeformat: "%d.%m.%y",
minTickSize: [1,"day"],
min: (new Date(2011,5,25)).getTime(),
max: (new Date(2011, 5, 28)).getTime()
},
yaxis: {
mode: "number",
tickSize: 2
},
series: {
lines: { show: true },
points: { show: true }
}
});

Categories

Resources