Highcharts - tooltip time value does not match xAxis - javascript

I have a problem with a area chart that I have created.
The time in the tooltip does not correspond with the time on the xAxis (se image for example)
The time in the toolstip is right, the xAxis is however shifted two hours behind in time.
Settings for the chart (modified for brevity)
var chart = new Highcharts.Chart({
tooltip: {
dateTimeLabelFormats: {
day:"%A, %b %e, %Y, %H:%M"
},
formatter: function() {
var tt = '',
newDate = new Date(this.key).toLocaleString();
tt = '<b>' + newDate + ':</b> <br/>' + '<b>' + this.series.name + '</b>' + ': ' + this.y;
return tt;
}
},
xAxis: {
type: 'datetime'
}
});
This is how I draw the series:
for (var i = 0; i < newValue.length; i++) {
chart.series[0].addPoint([newValue[i].tValue, newValue[i].value], false, false);
}
newValue[i].tValue is in epoch, for example 1493097600000

In my case setting useUTC to false helped.
Highcharts.setOptions({
global: {
useUTC: false
}
});

Related

Fusioncharts Real-time Line anchorbgclor

I want to use anchorBgColor attribute for Real-time Line chart.
Real-time Line chart.
function updateData() {
var t = new Date(),
date =
t.getHours() + ":" + t.getMinutes() + ":" + t.getSeconds(),
val = Math.floor(Math.random() * (7800 - 7200 + 1)) + 7200,
strData = "&label=" + date + "&value=" + val;
// Feed it to chart.
chartRef.feedData(strData);
}
Could you recommend how to change anchorBgColor for this chart?
If you are wanting to have all the points the same color all you have to do is include the anchorBgColor property in the chart object
{
...
dataSource: {
chart: {
...
anchorBgColor: "#26aa5a"
}
}
}
If you want points to change colors as you add them you have manipulate the chart data object and use setJSONData rather than using the feedData method.
<div id="chart-container">FusionCharts will render here</div>
FusionCharts.ready(function() {
var chartObj = new FusionCharts({
type: 'line',
renderAt: 'chart-container',
id: 'myChart',
width: '500',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"theme": "fusion",
"anchorRadius": "6",
"theme": "fusion"
},
"data": []
}
});
chartObj.render();
function pushNewPoint() {
var t = new Date(),
date =
t.getHours() + ":" + t.getMinutes() + ":" + t.getSeconds(),
val = Math.floor(Math.random() * (7800 - 7200 + 1)) + 7200,
randomColor = Math.floor(Math.random()*16777215).toString(16)
newEntry = {
label: date,
value: val,
anchorBgColor: "#" + randomColor
}
chartData = chartObj.getChartData('json')
chartData.data.push(newEntry)
chartObj.setJSONData(chartData)
}
var counter = 0;
var i = setInterval(function(){
pushNewPoint()
counter++;
if(counter === 10) {
clearInterval(i);
}
}, 1000);
});
Example can be seen here

highcharts from HTML table does not getting the x axis key

I am using a highcharts to draw chart from HTML table , my problem is i want to custom the tooltip but the "this.x" or "this.key" returned as decimal number not as string, how can I get the x axis value as it is??
and that's my code:
Highcharts.chart('ChartContainer', {
data: {
table: 'tblData'
},
chart: {
type: 'line'
},
title: {
text: ''
},
yAxis: {
allowDecimals: false,
title: {
text: ''
}
},
tooltip: {
useHTML: true,
formatter: function () {
return GetCustomTooltip(this.series.name, this.y, firstSeriesToolTip, firstTooltipTitle, secondTooltipTitle, this.zvalue);
}
}
});
function GetCustomTooltip(xvalue, yvalue, TooltipArray, firstTooltipTitle, secondTooltipTitle, zvalue, thirdTooltipTitle) {
var tooltipMessage = '';
for (var i = 0; i < TooltipArray.length; i++) {
if (TooltipArray[i][0]== xvalue) {
tooltipMessage += '<b>' + xvalue + '</b><br>';
tooltipMessage += firstTooltipTitle + ': ' + '<b>' + yvalue + '</b><br>';
if (secondTooltipTitle != null)
tooltipMessage += secondTooltipTitle + ': ' + '<b>' + TooltipArray[i][1] + '</b><br>';
if (thirdTooltipTitle != null)
tooltipMessage += thirdTooltipTitle + ': ' + '<b>' + TooltipArray[i][3] + '</b><br>';
break;
}
}
return tooltipMessage;
}
and the table I build it dynamically before draw the chart.
I got the right values when I change the xAxis type to category

How to include data from point in Highcharts xAxis label?

I am trying to include some extra data from my points in the xAxis label of a Highcharts line chart.
I'm creating my points like this. xAxis is 'datetime' type, and I'm using custom tickPositions (this part works fine).
for (row of results) {
var point = {x:Date.parse(row.time), y:row.value, magicNumber:row.ID};
data_series.data.push(point);
chartConfig.xAxis.tickPositions.push(Date.parse(row.time));
}
In the tooltip I'm able to do the following (this works):
tooltip: {
formatter: function() {
return 'ID: ' + this.point.magicNumber + ' Value:' + this.point.y.toFixed(3);
},
},
How do I do the equivalent in the xAxis formatter? Not clear from the docs if this is possible.
xAxis: {
type: 'datetime',
labels: {
rotation: 90,
formatter: function () {
var ID = **What goes here to obtain magicNumber?**
var datetime = new Date(this.value);
return ID.toString() + ' ' + datetime.toISOString();
}
},
tickPositions: []
}
Try this, console.log(this); should give you a hint if my solution doesn't works.
xAxis: {
type: 'datetime',
labels: {
rotation: 90,
formatter: function () {
console.log(this);
var ID = this.chart.series[0].data[this.pos].magicNumber;
var datetime = new Date(this.value);
return ID.toString() + ' ' + datetime.toISOString();
}
},
tickPositions: []
}
Both formatters has different context, so one way out of that is by iterate on every point of your data (inside of the xAxis.labels.formatter function), find the point which has the same x as this.value, and assign it to some variable. It should be enough, but there is a likelihood of a returning empty object, when none of points won't fit to the tick value.
xAxis: {
type: 'datetime',
labels: {
formatter() {
var points = this.chart.userOptions.series[0].data
var sameTimestampPoint = points.filter(p => p.x === this.value)[0]
var magicValue = sameTimestampPoint ? sameTimestampPoint.magicValue : ""
return magicValue + '<br/>' + this.value
}
}
}
Live example: https://jsfiddle.net/2r8z5wny/

Highcharts legend hiding wrong data

The legend in my highcharts is not functioning correctly. I have 2 series, each named differently. When I click on 'series1' on the legend, the data for 'series1' is hidden leaving 'series2' behind. However, when I click on 'series2' first, all the data is hidden instead of only 'series2'. What are some common mistakes that could lead to this? Here is a snippet of the involved code:
EDIT: Here is a jsFiddle reproduction of my bug. You can see when you click on "Pool" in the legend both series are removed. Clicking on client, however, works as expected. https://jsfiddle.net/LLExL/5616/
EDIT2: I found the solution. Apparently if the first index of a given series of data is empty, the error occurs. It also appears that it must have the same number of elements equal to the index with the least amount of data points. So in my case, I check if the first element in clientChartData or poolChartData is empty, if so I append 5 pairs of quotes to that array.
$('#all-cpus').highcharts({
chart: {
type: 'boxplot',
inverted: true
},
title: {
text: 'All CPUs'
},
xAxis: {
title: { text: 'Hybrids' }
},
yAxis: {
title: { text: 'Yield' }
},
legend: { enabled: true },
credits: { enabled: false },
tooltip: {},
plotOptions: {
boxplot: {
fillColor: '#6c3a38',
lineWidth: 3,
medianWidth: 3,
stemColor: '#DF5353',
stemDashStyle: 'dot',
stemWidth: 1,
whiskerColor: '#AAEEEE',
whiskerLength: '20%',
whiskerWidth: 3
}
},
series: [
{ name: 'Client' },
{ name: 'Pool' }
]
});
Here is where I set the chart data. Assume organizedClientData as all the data I need.
//Set the data to be displayed on the chart
clientChartData = organizedClientData;
$chart.highcharts().series[0].setData(clientChartData, false);
$chart.highcharts().series[0].update({name: this.clientData.name}, false);
$chart.highcharts().series[1].setData(poolChartData, false);
$chart.highcharts().series[1].update({name: this.poolData.name}, false);
//Set tooltip info to reflect dynamic data and to include acres
$chart.highcharts().tooltip.options.formatter = function() {
var index = this.point.x;
var numAcresPool = poolAcres[ index ];
var numAcresClient = clientAcres[ index ];
var tooltipString = this.point.category + '<br>' +
this.point.series.name + '<br>' +
'Max: ' + this.point.high + '<br>' +
'Upper Quartile: ' + this.point.q3 + '<br>' +
'Median: ' + this.point.median + '<br>' +
'Lower Quartile: ' + this.point.q1 + '<br>' +
'Min: ' + this.point.low + '<br>';
//Handle client vs. pool acreage display, and check if on the 'All Cpus' tab
if(this.point.series.name == 'Pool') {
tooltipString = tooltipString + 'Acres: ' + numAcresPool;
}
else if(this.point.series.name == 'All Farms' /*&& $chart.selector != '#all-cpus'*/) {
tooltipString = tooltipString + 'Acres: ' + numAcresClient;
}
return tooltipString;
};
var xaxis = $chart.highcharts().xAxis[0];
var title = { text: this.getProfileData().cropId == 1 ? 'Hybrids' : 'Varieties' };
xaxis.setCategories(categories, true);
xaxis.setTitle(title, true);
$chart.highcharts().setSize( $chart.parent().width() - 15, $chart.highcharts().xAxis[0].categories.length * 50 + 150 );
$chart.highcharts().redraw();
This looks like a bug, I reported that to our developers here: https://github.com/highcharts/highcharts/issues/4939

jqPlot X-axis rendering

I've combined a jquery datepicker widget with jqplot, and am using the values of the datepicker to recreate the plot when something changes.
However, during large date ranges, the labels on the x-axis run together to look very ugly.
Here's it regularly:
Here's it with a large range:
My question is -- is it possible to change the rendering of the axis, so if there is a large range that not every single date shows? Maybe 2 or 3, but always including the beginning date and end date.
Here's my code -- please let me know if you can help!
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
async: false,
url: url,
type: "GET",
dataType:"json",
data: {metricName: ""},
success: function(data) {
ret = data;
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
return ret;
};
//var jsonurl = "reports/reportData.json";
var jsonurl = "tenant/metrics/get.json";
var currentTime = new Date()
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var today = month + "-" + day + "-" + year;
var currentDatePlus = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var dayPlus = currentDatePlus.getDate()
var monthPlus = currentDatePlus.getMonth() + 1
var yearPlus = currentDatePlus.getFullYear()
var tomorrow = monthPlus + "/" + dayPlus + "/" + yearPlus;
function getLastWeek(){
var today = new Date();
var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
return lastWeek ;
}
var lastWeek = getLastWeek();
var lastWeekMonth = lastWeek.getMonth() + 1;
var lastWeekDay = lastWeek.getDate();
var lastWeekYear = lastWeek.getFullYear();
var lastWeekDisplay = lastWeekMonth + "/" + lastWeekDay + "/" + lastWeekYear;
var datepickerBegin = $("#datepicker_start").val();
var datepickerEnd = $("#datepicker_to").val();
$('#applyBtn').click( function() {
// Check to make sure the datepicker isn't empty
if ($("#datepicker_start").val() !== "" && $("#datepicker_to").val() !== "") {
var datepickerBegin = $("#datepicker_start").val();
var datepickerEnd = $("#datepicker_to").val();
//Recreate the plot
var plot2 = $.jqplot('chart2', jsonurl,{
title: "",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {unusedOptionalUrl: jsonurl},
axes: {
xaxis: {
//'numberTicks' : 7,
min: datepickerBegin,
max: datepickerEnd,
renderer:$.jqplot.DateAxisRenderer,
rendererOptions:{tickRenderer:$.jqplot.CanvasAxisTickRenderer},
tickInterval: '1 day',
tickOptions:{formatString:'%#m/%#d/%Y'
}
//rendererOptions: {sdaTickInterval: [1, 'month']}
},
yaxis: {
label: "MB",
tickOptions:{formatString:'%d '},
// Comment the next line out to allow negative values (and therefore rounded ones)
min: 0
}
},
highlighter: {
show: true,
sizeAdjust: 7.5
}
});
//redraw the plot now.
//plot2.reInitialize({});
plot2.replot({});
}
})
// The default plot
var plot2 = $.jqplot('chart2', jsonurl,{
title: "",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {unusedOptionalUrl: jsonurl},
axes: {
xaxis: {
//'numberTicks' : 7,
min: lastWeekDisplay,
max: tomorrow,
renderer:$.jqplot.DateAxisRenderer,
rendererOptions:{tickRenderer:$.jqplot.CanvasAxisTickRenderer},
tickInterval: '1 day',
tickOptions:{formatString:'%#m/%#d/%Y'
}
//rendererOptions: {sdaTickInterval: [1, 'month']}
},
yaxis: {
label: "MB",
tickOptions:{formatString:'%d '},
// Comment the next line out to allow negative values (and therefore rounded ones)
min: 0
}
},
highlighter: {
show: true,
sizeAdjust: 7.5
}
});
});
Okay - I've got a better grasp on this issue.
I've limited the tick number using the 'numberTicks' property, so it has a certain number if the date range is over a specificed value.
The only issue left is that, with numberTicks, the intersections aren't always correct (meaning that on the x-axis 10/05/12, the value isn't always placed there when numberTicks is limited.

Categories

Resources