Highcharts, Set XAXIS only show certain time/number - javascript

I want to create chart like this with highcharts, it is possible to set xAxis like image below?
I try to use tickpoints and tickinterval but still didn't get the result I wanted
Sample of actual data,
This is result I get now, i want to change xaxis into interval 30 minutes like first image
My code
$.ajax({
url: "",
type: 'GET',
dataType:'json',
success: function(data) {
// console.log(data) ;
var chartSeriesData=[];
var chartCatData=[];
$.each(data, function(i,item){
var series_name = item.time;
var series_data = item.power;
chartSeriesData.push(series_data);
chartCatData.push(series_name);
});
Highcharts.chart('power', {
title: {text: ''},
subtitle: {text: ''},
yAxis: {
title: {text: ''}
// ,min: 0, max: 0.010
},
xAxis: {
categories: chartCatData,
title: {
text: ''
},
labels: {
enabled: true
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
}
}
},
series: [
{
// name: 'Power',
data: chartSeriesData
}
],
Result console.log(data)

You should use datetime axis type and format your x values as timestamps in milliseconds.
const chartSeriesData = data.map(
item => [new Date(item.date).getTime(), item.power]
);
Highcharts.chart('container', {
xAxis: {
type: 'datetime',
tickInterval: 1000 * 60 * 30
},
series: [{
data: chartSeriesData
}]
});
Live demo: http://jsfiddle.net/BlackLabel/vzepscjr/
API Reference: https://api.highcharts.com/highcharts/xAxis

Related

Passing items into array and keeping format?

I am trying to do a drilldown chart like this one http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-drilldown/ and I am pretty close but I am trying loop my output of my items into an array and get the same format as the demo drilldown chart however it seems to only be getting the last set of items in my each loop. How can I keep the same format and pass them into my array? https://jsfiddle.net/pwbz0mxy/
chart_user_hours = {
chart: {
type: 'column',
renderTo: 'hours_chart_container'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Total Hours'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.2f}'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}</b> of total<br/>'
},
series: [],
drilldown: {
series: []
}
};
data = '{"comparison":false,"title":"User Capacity Breakdown | January 2016 to July 2016","series":{"name":"User Hours Breakdown ","colorByPoint":true,"data":{"series":{"data":[{"name":"test","y":10,"drilldown":"test"},{"name":"test","y":154,"drilldown":"test"},{"name":"Large Move","y":29,"drilldown":"Large Move"},{"name":"Invoice 78554","y":20,"drilldown":"Invoice 78554"},{"name":"Small Move*","y":13,"drilldown":"Small Move*"}]}}},"drilldown":{"drilldown":{"series":[{"name":"test","id":"test","work_date":["2016-06-10"],"data":[10]},{"name":"test","id":"test","work_date":["2016-07-11","2016-07-10","2016-07-08","2016-07-06"],"data":[37,51,44,22]},{"name":"Large Move","id":"Large Move","work_date":["2016-07-04","2016-07-05","2016-07-08","2016-07-11"],"data":[9,8,7,5]},{"name":"Invoice 78554","id":"Invoice 78554","work_date":["2016-06-14","2016-06-24"],"data":[10,10]},{"name":"Small Move*","id":"Small Move*","work_date":["2016-06-30","2016-06-03"],"data":[3,9]}]}}}';
var obj = $.parseJSON(data);
chart_data = typeof obj.series.data.series != 'undefined' ? obj.series.data.series.data : '';
chart_user_hours['series'] = [{
name: obj.series.name,
data: chart_data
}];
$.each(obj.drilldown.drilldown.series, function( key, value ) {
chart_user_hours['drilldown']['series'] = [{
name: value.work_date,
id: value.id,
data: value.data
}];
});
var chart_hours = new Highcharts.Chart(chart_user_hours);
You are replacing the value of chart_user_hours['drilldown']['series'] each time in your loop. So actually it has to look like this:
Declaring the array – Before Loop
chart_user_hours['drilldown']['series'] = [];
Use push function of the array to add the value at the end of your array – In Loop
chart_user_hours['drilldown']['series'].push({
name: value.work_date,
id: value.id,
data: value.data
});

Loading millions of points with Highcharts

I have a json dataset with millions of points.The structure is like this:
[[1436997600000,7],[....]]
The first number is a data and second one is a value.
I want to plot this in a highchart so that it doesn't take so much time to load the chart and to navigate in it. I followed this example: http://www.highcharts.com/stock/demo/lazy-loading
but can't get it work with my data. It take so much time to load and when I zoom the message 'loading from server' doesn't disappear. Can anyone help me on this please?
JS:
$(function () {
/**
* Load new data depending on the selected min and max
*/
function afterSetExtremes(e) {
var chart = $('#container').highcharts();
chart.showLoading('Loading data from server...');
$.getJSON('http://localhost/public_html/webservice.php/re/pap/' + Math.round(e.min) + '/' + Math.round(e.max), function (data) {
chart.series[0].setData(data);
chart.hideLoading();
});
}
// See source code from the JSONP handler at https://github.com/highcharts/highcharts/blob/master/samples/data/from-sql.php
$.getJSON('http://localhost/public_html/webservice.php/re/pap', function (data) {
// Add a null value for the end date
data = [].concat(data, [[Date.UTC(2016, 9, 14, 19, 59), null]]);
// create the chart
$('#container').highcharts('StockChart', {
chart : {
type: 'scatter',
zoomType: 'x'
},
navigator : {
adaptToUpdatedData: false,
series : {
data : data
}
},
scrollbar: {
liveRedraw: false
},
title: {
text: 'AAPL history by the minute from 1998 to 2011'
},
subtitle: {
text: 'Displaying 1.7 million data points in Highcharts Stock by async server loading'
},
rangeSelector : {
buttons: [{
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'day',
count: 1,
text: '1d'
}, {
type: 'month',
count: 1,
text: '1m'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false, // it supports only days
selected : 4 // all
},
xAxis : {
events : {
afterSetExtremes : afterSetExtremes
},
minRange: 3600 * 1000 // one hour
},
yAxis: {
floor: 0
},
series : [{
data : data,
dataGrouping: {
enabled: false
}
}]
});
});
});
Fiddle: http://jsfiddle.net/f0u5c4pg/
Thanks in advance!

how to create a column char with highcharts where each column has a different color

I´ve a chart using highcharts, the only problem is that each column has the same column.
What should I do so each column has a different column.
Here is my code:
var charts = [];
$containers = $('#container1');
var datasets = [
{
name: 'Tokyo',
data: [49, 57]
}];
var cat = ['A', 'B'];
console.log(datasets);
$.each(datasets, function(i, dataset) {
console.log(dataset);
charts.push(new Highcharts.Chart({
chart: {
renderTo: $containers[i],
type: 'column',
marginLeft: i === 0 ? 100 : 10
},
title: {
text: dataset.name,
align: 'left',
x: i === 0 ? 90 : 0
},
credits: {
enabled: false
},
xAxis: {
categories: cat,
labels: {
enabled: i === 0
}
},
yAxis: {
allowDecimals: false,
title: {
text: null
}
},
legend: {
enabled: false
},
series: [dataset]
}));
});
Thanks in advance.
To have each column be a different color, all you have to do is set the colorByPoint property to true.
Reference:
http://api.highcharts.com/highcharts#plotOptions.column.colorByPoint
Alternatively you can make each column a separate series, which gives you additional levels of control.
OTOH, in the majority of cases, having each column a separate color serves no purpose except to clutter and confuse the data, and make the user work harder cognitively to interpret the chart.
If you want to highlight a single column for a particular reason, you can do that by adding the fillColor property to the data array:
Something like:
data:[2,4,5,{y:9,fillColor:'rgba(204,0,0,.75)',note:'Wow, look at this one'},4,5,6]
I finally found a way to show more than 1 color for each column:
var charts1 = [];
var $containers1 = $('#container1');
var datasets1 = [{
name: 'Dalias',
data: [29]
},
{
name: 'Lilas',
data: [1]
},
{
name: 'Tulipanes',
data: [15]
}];
$('#container1').highcharts({
chart: {
type: 'column',
backgroundColor: 'transparent'
},
title: {
text: 'Montos pedidos por división'
},
tooltip: {
pointFormat: '<span style="color:{series.color};" />{series.name} </span>:<b>{point.y}</b>',
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
},
series : {
cursor: 'pointer',
point: {
events: {
/*click: function() {
verDetalle("Especialidades,"+ this.series.name);
}*/
}
}
}
},
credits:{
enabled: false
},
yAxis: {
min: 0,
title: {
text: ''
}
},
xAxis: {
categories: ['División']
},
series: datasets1
});

How do I make a Tornado Chart using Highcharts

I am trying to prepare a Tornado Chart using the column chart in Highcharts. Here is my fiddle.
My current code is:
$('#container').highcharts({
chart: {
type: 'columnrange',
inverted: true
},
title: {
text: 'Net Sales'
},
subtitle: {
text: 'MM $'
},
xAxis: {
categories: ['Annual Revenue', 'Number of Years', 'Annual Costs']
},
yAxis: {
title: {
text: 'MM $'
}
},
plotOptions: {
columnrange: {
dataLabels: {
enabled: true,
formatter: function () {
return this.y;
}
}
},
scatter:{
marker:{
symbol:'line',
lineWidth:11,
radius:8,
lineColor:'#f00'
}
}
},
legend: {
enabled: false
},
series: [{
name: 'Temperatures',
data: [
[12.15, 46.86],
[15.45, 42.28],
[27.77, 31.24]
]
},
{
name:'Base',type: 'scatter',data:[120],
}]
});
The problem is that the last series (Annual Costs) does not show, as it is in reversed order. Also, I'd like the Tornado Chart to look more like this:
Note that the labels in this chart are different from the actual values plotted. Also note that the bar in the center - in the example code, there would be a vertical line at 29.5. I would also like to support a combined uncertainty bar like the one at the bottom. Any suggestions would be greatly appreciated.
Your last bat is not showing, because first number is lower than second, see: http://jsfiddle.net/kErPt/1/
If you want to display another values at labels, then add that info first. Example:
data: [{
low: 12,
high: 15,
lowLabel: 35,
highLabel: 46
}, {
low: 2,
high: 35,
lowLabel: 15,
highLabel: 26
} ... ]
And then use dataLabels.formatter for series.
To add vertical line use plotLines.
I'm not sure what is the last bar called 'combined uncertainty'.
I've used Highcharts with separate series (thanks jlbriggs) to create a Tornado Chart: http://jsfiddle.net/uRjBp/
var baseValue = 29.5;
var outputTitle = "Net Sales";
var chart = new Highcharts.Chart({
chart: {
renderTo:'container',
//type:'column'
//type:'area'
//type:'scatter'
//type:'bubble'
},
credits: {},
exporting: {},
legend: {},
title: {
text: outputTitle
},
subtitle: {
text: "MM $"
},
tooltip: {
formatter: function() {
var msg = "";
var index = this.series.chart.xAxis[0].categories.indexOf(this.x);
var low = round(this.series.chart.series[0].data[index].y+baseValue);
var high = round(this.series.chart.series[1].data[index].y+baseValue);
if (this.x === "Combined Uncertainty") {
msg = "Combined Uncertainty in "+outputTitle+": "+low+" to "+high;
} else {
var lowLabel = this.series.chart.series[0].data[index].label;
var highLabel = this.series.chart.series[1].data[index].label;
msg = '<b>'+outputTitle+'</b> goes from '+ low +' to '+ high+'<br/> when '+this.x +
' goes from <br/> '+lowLabel+" to "+highLabel;
}
return msg;
}
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
formatter: function () {
var index = this.series.chart.xAxis[0].categories.indexOf(this.x);
if (this.series.userOptions.labels === undefined) {
return this.y+baseValue;
}
return this.key === "Combined Uncertainty" ? "":this.series.userOptions.labels[index];
}
}
}
},
xAxis: {
title: {
text: 'Factor'
},
allowDecimals:false,
categories: ['Annual Revenue', 'Number of Years', 'Annual Costs', 'Combined Uncertainty']
},
yAxis: {
title: {
text: 'MM $'
},
labels: {
formatter:function() {
return this.value+baseValue;
}
}
},
series:[{
name: 'Low',
grouping:false,
type:'bar',
data:[{y:12.15-baseValue, label:10},{y:15.45-baseValue, label:1},{y:31.25-baseValue, label:2},{y:12.15-baseValue, color:'#99CCFF', label: ""}],
labels:[10,1,2,]
},{
name: 'High',
grouping:false,
type:'bar',
data:[{y:46.86-baseValue, label:30},{y:42.28-baseValue, label:3},{y:27.77-baseValue, label:4},{y:46.86-baseValue, color:'#99CCFF', label:""}],
labels:[30,3,4,]
},
{
name: 'Median',
type: 'scatter',
data: [null,null, null,27-baseValue],
marker: {
lineWidth: 2,
lineColor: Highcharts.getOptions().colors[3],
fillColor: 'white'
}
}]
});
function round(num) {
return Math.round(num*100)/100;
}
usually, this kind of chart is done using a separate series for the left and right portions
One way to do this is by setting one set of data as negative numbers, and then using the formatters to make the axis labels, datalabels, and tooltips display the absolute values
example:
http://jsfiddle.net/jlbriggs/yPLVP/68/
UPDATE:
to show a line as in your original chart, you can extend the marker symbols to include a line type, and use a scatter series to draw that point:
http://jsfiddle.net/jlbriggs/yPLVP/69/
If you don't want to have the extra code for the line marker type, you could use any of the other existing marker symbols for the scatter series.

highchart json data points

I am breaking my head over this one.
i have an highchart with Json data. now would like to split the Json data in to 2 data points.
json data;
[1340283205000,5,32]
Explanation
time, number, number
The current chart works with time, number. Now i have added another datapoint but that dows not work.
function requestData() {
$.ajax({
url: 'php/hits_json.php',
success: function(point) {
var series = chart1.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart1.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 5000);
},
cache: false
});
}
$(document).ready(function() {
window.chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'areaspline',
events: {
load: requestData
}
},
title: {
text: 'Hits per 5 sec'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 100,
maxZoom: 10 * 10000
},
yAxis: {
min: 0,
minPadding: 0.25,
maxPadding: 0.1,
title: {
text: 'Hits',
margin: 40
}
},
plotOptions: {
series: {
dataLabels: {
enabled: true
},
marker: {
enabled: true
},
}
},
credits: {
enabled: false
},
series:
[{
name: 'Hits',
data: [0],lineWidth: 1
},{
name: 'Requests',
data: [0],lineWidth: 1
}]
});
});
Can someone point me in the right direction to solve my issue :)
Thnx in advance
You do not have the data labeled in your json. So the first two values are treated as x and y and the third is ignored. To properly format your data do something like the following:
var json = [
{
"x":1340283205000,
"y":5
},
{
"x":1340283205000,
"y":32
}];

Categories

Resources