I am working with the Highstock compare demo:
http://www.highcharts.com/stock/demo/compare
jsFiddle:
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/stock/demo/compare/
The associated code of the percent compare is as follows:
plotOptions: {
series: {
compare: 'percent'
}
},
If we set the rangeSelector to 1m (one month), and assuming today is August 15, 2016, then the first entry displayed is Tuesday, July 12. The values are MSFT: 53.21, AAPL: 97.42, and GOOG: 720.64. The Tooltip shows percentage changes of +1.18%, +0.45%, and +0.78%, respectively, over the previous day. But the problem is that the values for the previous day (7/11/2016) are not shown. This is confusing to the user, in my opinion. What I want to do instead is give each of these starting values a percentage change of 0%, so the left-side of the graph always starts at the origin. How do I do this?
UPDATE: I was thinking along the lines of something like this:
events: {
load: function(e) {
set_new_min_y_data_points(e);
}
}
// ...
function set_new_min_y_data_points(e) {
for (var i = 0; i < e.target.series.length; ++i) {
// By setting the first data point to the same
// value as the second data point, we ensure
// that the series starts at the origin.
e.target.series[i].processedYData[0] = e.target.series[i].processedYData[1];
}
}
...but this doesn't work. Even though the values of e.target.series[i].processedYData[0] are changed, the graph looks the same.
Related
I'm using highcharts.js to visualize data series from a database. There's lots of data series and they can potantially change from the database they are collected from with ajax. I can't guarantee that they are flawless and sometimes they will have blank gaps in the dates, which is a problem. Highcharts simply draws a line through the entire gap to the next available date, and that's bad in my case.
The series exists in different resolutions. Hours, Days and Weeks. Meaning that a couple of hours, days or weeks can be missing. A chart will only show 1 resolution at a time on draw, and redraw if the resolution is changed.
The 'acutal' question is how to get highcharts to not draw those gaps in an efficient way that works for hous, days and weeks
I know highcharts (line type) can have that behaviour where it doesn't draw a single line over a gap if the gap begins with a null.
What I tried to do is use the resolution (noted as 0, 1, 2 for hour day or week), to loop through the array that contains the values for and detect is "this date + 1 != (what this date + 1 should be)
The code where I need to work this out is here. Filled with psudo
for (var k in data.values) {
//help start, psudo code.
if(object-after-k != k + resolution){ //The date after "this date" is not as expected
data.values.push(null after k)
}
//help end
HC_datamap.push({ //this is what I use to fill the highchart later, so not important
x: Date.parse(k),
y: data.values[k]
});
}
the k objects in data.values look like this
2015-05-19T00:00:00
2015-05-20T00:00:00
2015-05-21T00:00:00
...and more dates
as strings. They can number in thousands, and I don't want the user to have to wait forever. So performance is an issue and I'm not an expert here either
Please ask away for clarifications.
I wrote this loop.
In my case my data is always keyed to a date (12am) and it moves either in intervals of 1 day, 1 week or 1 month. Its designed to work on an already prepared array of points ({x,y}). Thats what dataPoints is, these are mapped to finalDataPoints which also gets the nulls. finalDataPoints is what is ultimately used as the series data. This is using momentjs, forwardUnit is the interval (d, w, or M).
It assumes that the data points are already ordered from earliest x to foremost x.
dataPoints.forEach(function (point, index) {
var plotDate = moment(point.x);
finalDataPoints.push(point);
var nextPoint = dataPoints[index+1];
if (!nextPoint) {
return;
}
var nextDate = moment(nextPoint.x);
while (plotDate.add(1, forwardUnit).isBefore(nextDate)) {
finalDataPoints.push({x: plotDate.toDate(), y: null});
}
});
Personally, object with property names as dates may be a bit problematic, I think. Instead I would create an array of data. Then simple loop to fill gaps shouldn't be very slow. Example: http://jsfiddle.net/4mxtvotv/ (note: I'm changing format to array, as suggested).
var origData = {
"2015-05-19T00:00:00": 20,
"2015-05-20T00:00:00": 30,
"2015-05-21T00:00:00": 50,
"2015-06-21T00:00:00": 50,
"2015-06-22T00:00:00": 50
};
// let's change to array format
var data = (function () {
var d = [];
for (var k in origData) {
d.push([k, origData[k]]);
}
return d;
})();
var interval = 'Date'; //or Hour or Month or Year etc.
function fillData(data, interval) {
var d = [],
now = new Date(data[0][0]), // first x-point
len = data.length,
last = new Date(data[len - 1][0]), // last x-point
iterator = 0,
y;
while (now <= last) { // loop over all items
y = null;
if (now.getTime() == new Date(data[iterator][0]).getTime()) { //compare times
y = data[iterator][1]; // get y-value
iterator++; // jump to next date in the data
}
d.push([now.getTime(), y]); // set point
now["set" + interval](now.getDate() + 1); // jump to the next period
}
return d;
}
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
series: [{
data: fillData(data, interval)
}]
});
Second note: I'm using Date.setDay() or Date.setMonth(), of course if your data is UTC-based, then should be: now["setUTC" + interval].
Using Highstock to chart a sorted time serie: [[timestamp, value], ...]
The datasource is sampled at irregular intervals. As result the distances between two points (in the time axis) varies.
If two adjacent points are separated for more than 5 minutes I want to show a gap in the chart.
Using the gapSize option doesn't work, because it doesn't allows to specify the 'size' of the gap as a function of time.
Showing gaps is already a part of Highstock, I just need a way to specify it as a fixed amount of time (5 minutes). Ideas?
Btw, beside that the plot works great.
Here's a slightly unclean way to "manipulate" gapSize to work so that it's value is the amount of milliseconds required to create a gap.
(function (H) {
// Wrap getSegments to change gapSize functionality to work based on time (milliseconds)
H.wrap(H.Series.prototype, 'getSegments', function (proceed) {
var cPR = this.xAxis.closestPointRange;
this.xAxis.closestPointRange = 1;
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
this.xAxis.closestPointRange = cPR;
});
}(Highcharts));
This utilizes that gapSize is only used within the getSegments function (see source), and it works based on the closestPointRange of the axis. It wraps the getSegments, sets closestPointRange to 1, calls the original method and then resets closestPointRange to its original value.
With the code above you could do gaps for 5 minutes like this:
plotOptions: {
line: {
gapSize: 300000 // 5 minutes in milliseconds
}
}
See this JSFiddle demonstration of how it may work.
Halvor Strand function wrapper did not work for me as long as getSegments is not part of highstock source code anymore to calculate that gap. Anyway, you can find an approximation to solve the problem combining this other topic and the previows answer like this:
(function(H) {
H.wrap(H.Series.prototype, 'gappedPath', function(proceed) {
var gapSize = this.options.gapSize,
xAxis = this.xAxis,
points = this.points.slice(),
i = points.length - 1;
if (gapSize && i > 0) { // #5008
while (i--) {
if (points[i + 1].x - points[i].x > gapSize) { // gapSize redefinition to be the real threshold instead of using this.closestPointRange * gapSize
points.splice( // insert after this one
i + 1,
0, {
isNull: true
}
);
}
}
}
return this.getGraphPath(points);
});
}(Highcharts))
setting gapSize in plotOptions to the desired size (in ms) like Halvor said:
plotOptions: {
line: {
gapSize: 300000 // 5 minutes in milliseconds
}
}
In case anyone comes across this and is spending hours trying to figure out why gapSize is not working like me. Make sure your time series data is sorted, only then will the gaps appear in the graph.
Another issue I ran into was my data series was in this format
[
{x: 1643967900000, y: 72},
{x: 1643967600000, y: 72},
{x: 1643967300000, y: 72}
]
However this does not seem to work with gapSize and needs to be in the format below
[
[1643967900000, 72],
[1643967600000, 91],
[1643967300000, 241]
]
I have 2 Series on one graph. Only one series can show at a time but the hidden graph affects the range on the x-axis.
The data is dynamically generated via PHP but here is 2 fiddles to show what I mean:
Fiddle With Changed Scale and Hidden Data
Fiddle With removed Hidden Data and correct scale
This code snippet is to ensure that only one series can be shown at any given time.
events: {
show: function () {
var chart = this.chart,
series = chart.series,
i = series.length,
otherSeries;
var seriesName = this['options']['name'];
chart.yAxis[0].axisTitle.attr({
text: seriesName
});
while (i--) {
otherSeries = series[i];
if (otherSeries != this && otherSeries.visible) {
otherSeries.hide();
}
}
}
I am not sure why the graph with the hidden data shows until 16:00 but the graph without any additional data shows until the last data point at 15:38
It appears that Highcharts is taking into account the pointRange of the series with the largest pointRange (although it is hidden) and displaying the x-axis based on that. The range of your "Calls/Hour" series is 1 hour, so it makes sure that if that series had a point at the very end, it would still have room to show.
I'm not sure if there's any elegant way of solving this, but a bit of a "hack" in your case is to change the pointRange of all series to that of the currently showing one.
My crude implementation of this has three changes to your code:
Your series that are visible: false by default also get pointRange: 1 so they don't disrupt the x-axis range for the only visible series.
When the chart has been created we store the correct point range of each series for future reference, for example with the callback function:
$('#callFrequencyGraph').highcharts({
// Options...
}, function(event) {
var series = this.series;
// Store the correct point ranges
for(var i = 0; i < series.length; i++) {
series[i].update({
historicalPointRange: (series[i].closestPointRange ? series[i].closestPointRange : 3600000)
}, false);
this.redraw();
}
}
Extend your events.legendItemClick function to update all series pointRange to that of the series which will be showing after the click is completed:
legendItemClick: function() {
if(this.visible){
return false;
}
else {
var series = this.chart.series;
for(var i = 0; i < series.length; i++) {
series[i].update({
pointRange: this.options.historicalPointRange
}, false);
}
}
}
See this updated JSFiddle for the result of all these changes.
Edit: jsFiddle Update for bug
I have a grid with 4 doughtnut charts on each column for different periods of time: last 90 days, last 60 days, last 7 days and today.
The problem with today is that it doesn't always show data, especially in the morning. Is there a way to force ChartJS to show the chart even if it doesn't have any data?
Here's an example: http://jsfiddle.net/6xV78/219/
var pieData = [
{
value: 0,
color:"#3F9F3F"
},
{
value : 0,
color : "#222"
}
];
I found a quick work-around, not sure how "good" or "valid" way it is but it's working for me. If the values are null/zero I replaced them with -1 to retain the looks of the chart and then use the custom tooltip function to override the output.
{
...
data: [earned == 0 ? -1 : earned, pending == 0 ? -1 : pending]
...
},
options: {
tooltip: {
callbacks: {
label: function (tooltipItem, data) {
const value = data['datasets'][0]['data'][tooltipItem['index']];
return '$' + (value == -1 ? 0 : value);
}
}
}
}
Obviously I have 2 slices and when both are 0 the chart is displayed with 2 equal halves both showing $0 income (both earned and pending).
*Do note that this will still take 1 into account when others aren't null so you need to take care of that on your end. I added a method to verify if ALL values are null and that's the only case I display it like this.
A pie chart with all values equal to zero is ill-defined. Because the angle (and the area) of each slice is proportionate to the ratio of the slice's respective value over the sum of all values. If all values are equal to zero, then their sum is zero. Division by zero should be rightfully avoided by the library (hopefully by design), resulting in the no-pie-chart case you encounter. It should be the programmer's responsibility to detect the all-zeros case before populating the chart, if such a case has a possibility of occurring. Then the programmer could either display a "No data yet. What are you doing up so early? Go to sleep." message, if all values are zero. Or, maybe, if they terribly need to keep the looks consistent (having a chart there all the time), they could show a special all-black no-data pie chart with the following dummy data:
var pieNoData = [
{
value: 1,
color: "#000000"
}
];
There is no shame in disclosing that no data exists yet, though.
I have this code to plot a chart which is invoked at a 5 second interval. How can I set the X axis to plot for a rolling 1 hour period?
/**
* Plot chart from retrieved quote data.
*/
function plotData() {
for(var i = 0; i < Quotes.length; ++i) {
if(dataSets[i].length == 7) dataSets[i].shift();
var timestamp = new Date().getTime();
dataSets[i].push([timestamp, Quotes[i].unitprice]);
}
var data = [];
for(var i = 0; i < Quotes.length; ++i) {
data.push({label: Quotes[i].stock, data: dataSets[i]});
}
$.plot('#livetrades-chart', data,
{ xaxis: { axisLabel: 'Time', axisLabelUseCanvas: true,
mode: 'time', timeformat: '%d/%m/%Y %H:%M:%S', timezone: TIME_ZONE },
yaxis: { axisLabel: 'Stock Price', axisLabelUseCanvas: true, tickDecimals: 2 }
});
}
Thanks.
The real-time updates example demonstrates rolling data, where each time a new point is added the oldest one is shifted off the array. What you want to do is basically identical, except with a time axis.
Edit: I still don't understand what the question is; your screenshot shows a time axis, and if you have an hour of data in your array (as opposed to the five seconds shown) then it will show an hour on the axis.
I think maybe you're confused about having to configure the x-axis in some way. You don't: if you provide data whose x-values are spaced an hour apart, the axis will fit to match it. The only thing you might need to tweak is the timeformat (see the Time Series section of the docs for more info) option, if you want the ticks to appear with only H:M:S rather than Y/M/D.
So as far as DNS suggests your cuestion is how did you setup the flot to updates also the xaxis.
here is a runing plunkr for that scenario.
http://plnkr.co/edit/TWpWhL?p=preview