Highchart with label in custom intervals - javascript

I have a Highchart bar graph (column type) which will show the data for each of the dates. Now it is getting the values through AJAX and date range
can be selected. Because of size limitations, I need to display the date labels in 5 day interval if the date range selected is more than 10 days.
That is all bars needs to be shown, but the interval for labels should be in 5 days interval if the date range is more than 10 days. If it is 10 days or lower, it should show all the dates.
My graph config is like the following :
var chart = new Highcharts.Chart({
credits: {
enabled: false
},
legend: {
align: 'right',
verticalAlign: 'top',
layout: 'vertical',
x: 20,
y: 10
},
chart: {
renderTo: 'id_name',
type: 'column'
},
xAxis: {
categories: dates,
crosshairs: true
},
yAxis: {
title: {
text: 'Y Axis Title'
}
},
colors: ['#1A7BB9', '#18A689', '#21B9BB', '#F7A54A', '#EC4758'],
title: {
text: 'My title goes here'
},
subtitle: {
text: 'my subtitle goes here'
},
series: PHP formatted data goes here
});

I'm not sure about the interval (every fifth label should be displayed? Or you want to compare time-range to determine that?), but in general you have two solutions:
easier one: disable dataLabels by default (series.dataLabels.enabled = false) but enable that for a specific points, for example:
series: [{
data: [{
x: timestamp_1,
y: timestamp_1,
dataLabels: {
enabled: true
}
}, [timestamp_2, value_2], [timestamp_3, value_3], ... , {
x: timestamp_N,
y: timestamp_N,
dataLabels: {
enabled: true
}
}]
}]
harder one: wrap drawDataLabels method, and remove unnecessary labels:
(function (H) {
H.wrap(H.seriesTypes.column.prototype, 'drawDataLabels', function (p) {
var step = H.pick(this.options.dataLabels.step, 0),
iterator = 0;
p.call(this);
if(step) {
H.each(this.points, function (point) {
if (point.dataLabel) {
if (iterator % step !== 0) {
point.dataLabel = point.dataLabel.destroy();
}
iterator ++;
}
});
}
});
})(Highcharts)
jsFiddle for the second solution: http://jsfiddle.net/gL2kw73b/2/

Related

Multiple series of data in Highcharts but second line graph is displayed squashed?

I'm pretty new in using Highcharts API and, just started to embark using its cool features. I have a ASP.NET MVC web application which plot a line graph from a data source. In my application a user selects a key value from a list box and, out of that key an array of values will be retrieved and used the data as series for the graph.
[Chart 1] This is the plotted highchart.
[Chart 2] This is the expected output
As you can see in the above screenshots, CDT158 series displayed the graph correctly, more similar to Chart 2. But, Series 2 in Chart 1 is squashed, it is supposed to be like in Chart 2 - SINUSOID.
This is my functions that prepares and display the chart
var myChart;
function prepareChartData(dataChart)
{
var xAxis = [];
var dataSeries = [];
var xTitle;
for (var i = 0; i < dataChart.length; i++) {
var items = dataChart[i];
var XcategoriesItem = moment(items.Time).format("DD-MMM-YYYY HH:mm:ss");
var seriesData = parseFloat(items.Value);
xAxis.push(XcategoriesItem);
dataSeries.push(seriesData);
xTitle = items.Name;
}
if (myChart == undefined)
{
plotChartData(xAxis, dataSeries, xTitle);
return;
}
myChart.addSeries({
title: xTitle,
data: dataSeries
});
};
function plotChartData(Xaxis, dataseries, xtitle)
{
myChart = new Highcharts.Chart({
chart: {
renderTo: 'svgtrendspace',
type: 'line',
zoomType: 'xy',
panning: true,
panKey: 'shift',
plotBorderWidth: 1
},
title: {
text: 'Sample Chart'
},
legend: {
layout: 'horizontal',
align: 'bottom',
horizontalAlign: 'middle',
borderWidth: 0
},
plotOptions: {
series: {
dataLabels: {
enabled: false,
format: '{y}'
},
allowPointSelect: false
}
},
xAxis: {
type: 'category',
categories: Xaxis,
labels: {
rotation: -65,
style: {
fontSize: '8px',
fontFamily: 'Verdana, sans-serif'
}
},
tickInterval: 60
},
yAxis: {
gridLineColor: '#DDDDDD',
gridLineWidth: 0.5
},
series: [{
name: xtitle,
data: dataseries,
//name: '',
//data: [],
tooltip: {
pointFormat: '{series.name}: <b>{point.y}</b><br/>',
valueDecimals: 2
}
}]
});
};
This is the div element that displays the chart
<div id="svgtrendspace" style="overflow:auto;display:table-row; height:100%;"></div>
The jquery post function that retrieves data from AE controller.
$.post("/AE/UpdateTrend", { TrendRequestData: jdata },
function (data) {
if (data.length > 4) {
var results = $.parseJSON(data);
console.log(results);
prepareChartData(results);
trendData = results;
}
else {
trendData = "";
FillNoData("#svgtrendspace");
$('#MinimumHorizontalLine').val("");
$('#MaximumHorizontalLine').val("");
}
});
What could go wrong in my highcharts configuration that made the second series line graph squashed?
Any help is greatly appreciated.
I think it's caused by using categories, but actually you want to use datetime axis. Categories for first series and the second one don't match and that's the result. In other words, I would:
Change data format for array of points:
for (var i = 0; i < dataChart.length; i++) {
var items = dataChart[i];
var xDate = +moment(items.Time);
var seriesData = parseFloat(items.Value);
dataSeries.push([xDate, seriesData]);
xTitle = items.Name;
}
Change type to "datetime" and remove categories:
xAxis: {
type: 'datetime', // type
// categories: Xaxis, // remove
labels: {
rotation: -65,
style: {
fontSize: '8px',
fontFamily: 'Verdana, sans-serif'
}
},
// tickInterval: 60 // remove that too - you don't want ticks every 60 milliseconds ;)
},

Highcharts second series name labeled to 'Series 2'?

Just started a week ago to learn and use Highcharts. In my application a user selects a key value from a list box and, out of that key an array of values will be retrieved and, used the data to create a multiple series of line graph. In the screenshot below the first series (in light blue color) has the name of CDEP158 and, on the second series (in black color), the series name shouldn't be 'Series 2', it should be CDT158. 'Series 2' for the second series is the issue here.
This is the chart data preparation code which accepts dataChart (result) from jquery post callback function called in a click event.
function prepareChartData(dataChart)
{
var dataSeries = [];
var xTitle;
for (var i = 0; i < dataChart.length; i++) {
var items = dataChart[i];
var xDate = +moment(items.Time);
var seriesData = parseFloat(items.Value);
dataSeries.push([xDate, seriesData]);
xTitle = items.Name;
}
if (aeChart === undefined || aeChart === null)
{
plotChartData(dataSeries, xTitle);
return;
}
aeChart.addSeries({
title: xTitle,
data: dataSeries
});
};
Function that creates a new instance of Highchart and its configuration:
function plotChartData(dataseries, xtitle)
{
aeChart = new Highcharts.Chart({
chart: {
renderTo: 'svgtrendspace',
type: 'line',
zoomType: 'xy',
panning: true,
panKey: 'shift',
plotBorderWidth: 1
},
title: {
text: ''
},
legend: {
layout: 'horizontal',
align: 'left',
itemDistance: 10,
borderWidth: 0,
itemMarginTop: 0,
itemMarginBottom: 0,
padding: 20
},
plotOptions: {
series: {
states: {
hover: {
enabled: false
}
},
dataLabels: {
enabled: false,
format: '{y}'
},
allowPointSelect: false
}
},
xAxis: {
type: 'datetime',
labels: {
rotation: -65,
style: {
fontSize: '9px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
gridLineColor: '#DDDDDD',
gridLineWidth: 0.5
},
series: [{
name: xtitle,
data: dataseries,
tooltip: {
pointFormat: '{series.name}: <b>{point.y}</b><br/>',
valueDecimals: 2
}
}]
});
};
Why is that the first series gets the correct name but on the second one it did not? Is my highcharts configuration wrong? How should I properly configure or format it to address the issue?
I have googled it for similar issues related with multiple series but I couldn't find any similar questions or answers that would help me.
The fact that it works for the first series implies that the issue isn't with your code, but rather is with your init.
Can you put a console.log('Title: ' + xTitle); statement right before you call aeChart.addSeries() in the above function to check on what you are passing in? My suspicion is that the second series is not being passed a title, and that HighCharts is therefore putting in Series2 on its own.
Maybe you should not be setting the value of xTitle in every single iteration of the initial for loop?

How can I get the yAxis of Highcharts to display categories instead of number values?

I have this fiddle JSfiddle
Here is the reproduced code:
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
xAxis: {
categories: ['Heroku', 'Ruby','Lisp','Javascript','Python','PHP']
},
yAxis: {
categories: ['low','medium','high'],
title: {
text: 'expertise',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ' millions'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
series: [{
data: ['low','high','low','medium','medium']
}]
});
});
If you look at the fiddle the yAxis does not render and has a value of for every x category. I've been looking at the highcharts api, but I can't seem to get this right. The code makes sense to me but I'm obviously doing something wrong. Can someone point out why the YAxis is not displaying correctly?
As mentioned in my comment, you need to supply the numeric value of the category, not the category name.
In the case of categories, the numeric value is the array index.
Also, in your case, the way you are trying to plot the values, I would add an empty category at the beginning, otherwise your first category of low gets plotted as 0, which doesn't seem right.
So,
categories: ['low','medium','high']
Becomes
categories: ['','low','medium','high'],
And
data: ['low','high','low','medium','medium']
Becomes
data: [1,3,1,2,2]
Updated fiddle:
http://jsfiddle.net/jlbriggs/k64boexd/3/
Check this fiddle:
http://jsfiddle.net/navjot227/k64boexd/2/
Trick is to utilize the formatter function. You can use a similar formatter function on y-axis labels too if that's desired. Though it seems like you need it for data labels for this problem.
$(function() {
$('#container').highcharts({
chart: {
type: 'bar'
},
xAxis: {
categories: ['Heroku', 'Ruby', 'Lisp', 'Javascript', 'Python', 'PHP']
},
yAxis: {
title: {
text: 'expertise',
align: 'high'
},
labels: {
overflow: 'justify',
}
},
tooltip: {
valueSuffix: ' millions'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true,
formatter: function() {
if (this.y == 0) {
return 'low'
} else if (this.y == 1) {
return 'medium'
} else {
console.log(this.y);
return 'high'
}
}
}
}
},
series: [{
data: [0, 2, 0, 1, 1]
}]
});
});
In my opinion, it is kinda unlikely for a line graph to have a y-axis category, since it speaks more of amount or value. In your case, "low, medium, and high" speaks of ranges, with which a certain value can be assigned to any of it.
Thus, Highcharts accepts series data in numeric form. But you can work around it by setting ['low', 'medium', 'high'] in the category attribute of yAxis, then setting series data as an array of number corresponding to the index of the category, i.e. [0,1,1,2,...] and tweaking the tooltip to display the category instead of the y value using formatter attribute.
Here is the code:
$(function() {
yCategories = ['low', 'medium', 'high'];
$('#container').highcharts({
title: {
text: 'Chart with category axes'
},
xAxis: {
categories: ['Heroku', 'Ruby','Lisp','Javascript','Python','PHP']
},
yAxis: {
categories: yCategories
},
tooltip: {
formatter: function() {
return this.point.category + ': ' + yCategories[this.y];
}
},
series: [{
data: [0, 1, 2, 2, 1]
}]
});
});
Here is a working example : JSFiddle

Highcharts multiple y axis with data from csv file

I've been creating charts on my company's website with data that is populated from a csv file. I need to add two additional y axes on the right side of the chart. I tried doing so by following Highchart's instructions, but my data is coming from a CSV file and I can't manage to get the two additional axes to connect to the data. Meaning, the other two splines look flat compared to the one that is actually plotting to it's y axis.
Below is the chart's JS file. The CSV file is 4 columns, which from left to right are Date, Overall, VIX, GSPC
Thank you in advance!
function basi_overall_chart() {
//var to catch any issues while getting data
var jqxhr_basi_overall = $.get('../../datafiles/basi/company_BASI_Overall_VIXSP.csv', function (data) {
var options = {
//chart options
chart: {
//set type of graph, where it renders
type: 'line',
renderTo: 'basi_overall_container'
},
//set title of graph
title: {
text: 'company Bid-Ask Spread Index (BASI)',
style: {
color: '#4D759E'
},
align: 'center'
},
//set xAxis title
xAxis: {
title: {
text: 'Date',
style: {
color: '#4D759E',
fontWeight: 'bold'
}
}
},
//set yAxis info
yAxis: [{
title: {
text: 'Basis Points (BPS)',
style: {
color: '#4D759E',
fontWeight: 'bold'
}
},
labels: {
//give y-axis labels commas for thousands place seperator
formatter: function () {
return Highcharts.numberFormat(this.value);
}
},
//set y-axis to the left side
opposite: false,
//set background grid line width
gridLineWidth: 1
}, { // Second yAxis
gridLineWidth: 1,
title: {
text: 'VIX',
style: {
color: '#de5a3c',
fontWeight: 'bold'
}
},
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value);
}
},
opposite: true
}, { // Third yAxis
gridLineWidth: 1,
title: {
text: 'SP',
style: {
color: '#4D759E',
fontWeight: 'bold'
}
},
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value);
}
},
opposite: true
}],
//stylize the tooltip
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>',
valueDecimals: 4
},
//enable and stylize the legend
legend: {
enabled: true,
layout: 'horizontal',
align: 'center',
borderWidth: 1,
borderRadius: 5,
itemDistance: 20,
reversed: false
},
//set the starting range. 0-5. 5="All", 4="1yr", etc
rangeSelector: {
selected: 5,
allButtonsEnabled: true
},
//set general plot options
plotOptions: {},
//disable credits
credits: {
enabled: false
},
//make download as csv format correctly
navigator: {
series: {
includeInCSVExport: false
}
},
//set name of chart downloads
exporting: {
filename: 'company_basi_overall',
//enable download icon
enabled: true,
//add image to download
chartOptions: {
chart: {
events: {
load: function () {
this.renderer.image('http://www.company.com/images/company_logo2.gif', 90, 75, 300, 48).attr({
opacity: 0.1
}).add();
}
}
},
//remove scrollbar and navigator from downloaded image
scrollbar: {
enabled: false
},
navigator:{
enabled: false
}
},
//make download as csv format correctly
csv: {
dateFormat: '%Y-%m-%d'
}
},
//set graph colors
colors: ['#002244', '#DBBB33', '#43C5F3', '#639741', '#357895'],
//series to be filled by data
series: []
};
//names of labels in order of series. make sure they are the same as series header in data file
var names = ['BASI', 'VIX', 'SP'];
//get csv file, multiply by 100 (divide by .01) and populate chart
readCSV(options, data, 1.0, names);
var chart = new Highcharts.StockChart(options);
})
//catch and display any errors
.fail(function (jqxhr_basi_overall, exception) {
ajaxError(jqxhr_basi_overall, exception, '#basi_overall_container');
});
}
(function () {
//set high level chart options for all charts
Highcharts.setOptions({
lang: {
thousandsSep: ','
}
});
$('.chart_container').toggle(false);
basi_overall_chart();
$('#basi_overall_container').toggle(true);
all_crossable_volume_chart();
auto_assign_toggle_chart_buttons();
})();

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.

Categories

Resources