Generate a line chart over column chart using highcharts - json

I am new to Highcharts and i like it.I am trying to create a line graph over column graph.but i make only column graph [link]http://jsfiddle.net/sunman/S9ChJ/
But here is my problem is i could not create a line graph upon column chart .so please tell me how it is possible.i have already searched for this and in that code i want change for line graph. so please help me
Here this code i am trying .but not shows me any graph
$(function () {
var chart;
$(document).ready(function() {
$('#container').highcharts({
chart: {
zoomType: 'xy'
},
title: {
text: 'Project faclityv Rating'
},
subtitle: {
text: 'testing'
},
xAxis: [{
categories: [A,B,C,D,E]
}],
yAxis: [{ // Primary yAxis
labels: {
// format: '{value} Rs.',
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'Bsp Cost',
style: {
color: Highcharts.getOptions().colors[1]
}
}
}, { // Secondary yAxis
title: {
text: 'facility rating',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
//format: '{value} out of 100',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 100,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
series: [{
name: 'Facility Rating',
type: 'column',
yAxis: 1,
data: [10,15,20,25,30],
tooltip: {
valueSuffix: ' out of 100'
}
}, {
name: 'Bsp Cost',
type: 'spline',
data: [5,10,15,20,25],
tooltip: {
valueSuffix: 'Rs.'
}
}]
});
$.getJSON("data.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0].data = json[1]['data'];
options.series[1].data = json[1]['data'];
chart = new Highcharts.Chart(options);
});
});
});
here is data.php
$query = mysql_query("SELECT projects_detail.Project_name,facility_rating.facilities_total,cost.bsp
FROM projects_detail LEFT OUTER JOIN facility_rating
ON projects_detail.project_id= facility_rating.project_id
LEFT OUTER JOIN cost ON facility_rating.project_id = cost.project_id");
$category = array();
$category['name'] = 'Project';
$series1 = array();
$series1['name'] = 'Facilities Rating';
$series2 = array();
$series2['name'] = 'BSP values';
while($r = mysql_fetch_array($query)) {
$category['data'][] = $r['Project_name'];
$series1['data'][] = $r['facilities_total'];
$series2['data'][] = $r['bsp'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series2);
print json_encode($result, JSON_NUMERIC_CHECK);

You need to add extra line serie.
json = [{
data: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']
}, {
data: [1, 2, 3, 1, 2, 3, 4, 1, 3, 3, 3, 3, 3, 3, 5, 1]
}];
options.xAxis.categories = json[0]['data'];
options.series[0].data = json[1]['data'];
options.series[1].data = json[1]['data'];
http://jsfiddle.net/S9ChJ/1/

Related

Highcharts stacked bar data from CSV

I'm trying to implement a stacked bar chart with data coming from a CSV.
I need to update series: with the data from the CSV file which contains, for example "John,10,5,3,4,1".
Help please!
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Stacked bar chart'
},
xAxis: {
categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
},
yAxis: {
min: 0,
title: {
text: 'Total fruit consumption'
}
},
legend: {
reversed: true
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}]
});
});
UPDT
I finally got it working, but still there's a problem. The bars are inverted and I need them to be exactly in the same order as in the CSV file.
Here's my parser:
$.get('chart.csv', function(data) {
var lines=data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
});
var chart = new Highcharts.Chart(options);
The contents of the CSV file:
Disconnection,30,30
Site Care,12,12
Documentation,35,35
Lining,22,22
Connection,70,52
I need the stacked bars in the same order as in the legend:
http://i.stack.imgur.com/6EkHg.png
You could try to custom setting the series indices before you render the chart to fix the inversion of the bars.
Something like this might do the trick:
for (var i = 0; i < options.series.length; i++) {
options.series[i].index = options.series.length - 1 - i;
options.series[i].legendIndex = i;
}

HighCharts issues in Dual axes, line and column charts

I am trying to generate Dual axes, line and column charts of highcharts .I have tried stackoverflows sugesstions but i couldn't find proper solution.I have the data formatted properly but yet the chart is not generate shows blank.I want this type of [link] http://jsfiddle.net/sunman/dwyNz/8/ .In spline line I want to show 'bsp values' and in column I want to show facilities_total. So below i show my code for this graph.I also pointed my error in index.php.
Here is my Index.php
$(function () {
$('#container').highcharts({
chart: {
zoomType: 'xy'
},
title: {
text: 'Project faclityv Rating'
},
subtitle: {
text: 'testing'
},
xAxis: [{
categories: []
}],
yAxis: [{ // Primary yAxis
labels: {
// format: '{value} Rs.',
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'Bsp Cost',
style: {
color: Highcharts.getOptions().colors[1]
}
}
}, { // Secondary yAxis
title: {
text: 'facility rating',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
//format: '{value} out of 100',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 100,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
series: [{
name: 'Facility Rating',
type: 'column',
yAxis: 1,
data: [],
tooltip: {
valueSuffix: ' out of 100'
}
}, {
name: 'Bsp Cost',
type: 'spline',
data: [],
tooltip: {
valueSuffix: 'Rs.'
}
}]
});
$.getJSON("combochart.php", function(json) {
options.xAxis.categories = json[0]['data']; /*error here: ReferenceError: options is not defined */
options.series[0] = json[1];
options.series[1] = json[2];
chart = new Highcharts.Chart(options);
});
});
Here is my combochart.php
$query1 = mysql_query("SELECT projects_detail.Project_name,superfac_rating.faci_total
FROM projects_detail LEFT OUTER JOIN superfac_rating
ON projects_detail.project_id= superfac_rating.project_id ");
$category = array();
$category['name'] = 'Project';
while($row1 = mysql_fetch_array($query1)) {
$category['data'][] = $row1['Project_name'];
$series1['data'][] = $row1['faci_total'];
}
$query2 = mysql_query("SELECT projects_detail.Project_name,superfac_rating.faci_total
FROM projects_detail LEFT OUTER JOIN superfac_rating
ON projects_detail.project_id= superfac_rating.project_id
LEFT OUTER JOIN cost ON gsuperfac_rating.project_id=cost.project_id ");
$series1 = array();
$series1['name'] = 'Project Name';
$series2 = array();
$series2['name'] = 'BSP VALUES';
while($row2 = mysql_fetch_array($query2)) {
$series1['data'][] = $row2['faci_total'];
$series2['data'][] = $row2['bsp'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series1);
array_push($result,$series2);
print json_encode($result, JSON_NUMERIC_CHECK);
I think i have problem in json code thats why i can't fetch data for graph.i checked in my console no errors.but i debug this code and json result shows me(json o/p writes in jsfiddle) but graph not appear in browser. i am explained in jsfiddle[link] jsfiddle.net/sunman/rDYvt/9 please check this. give me solution where i am wrong.So please help me and resolve my query.
Inside your $.getJSON("combochart.php", function(json) you need to setData like this
theChart.xAxis[0].setCategories(json[0]['data']);
theChart.series[0].setData(json[1]['data'], false);
theChart.series[1].setData(json[2]['data'], true);
Ok, it's working now...
Paste this in a JSFiddle to see it working...
$(document).ready(function() {
var json= '[{"name":"Project","data":["Green View","Grand","Arete","Canary Greens","Terra","Beethovens","Ninex City","South Park","Callidora","Lotus","Coban","NCR Green","Kocoon","Estella","NCR One"]},{"name":"Facilities Rating","data":[45,55,55,55,55,55,55,55,55,55,55,55,55,55,55]},{"name":"BSP VALUES","data":[97500,55745,16400,98700,38600,12090,94700,11400,12450,89500,86725,88335,54200,18200,30400]}]'
var jsobj = JSON.parse(json)
var firstSeriesData = [];
var secondSeriesData = [];
jsobj[1].data.forEach(function(seriesOneData){
firstSeriesData.push(seriesOneData);
})
jsobj[2].data.forEach(function(seriesTwoData){
secondSeriesData.push(seriesTwoData);
})
$('#container').highcharts({
chart: {
zoomType: 'xy',
type: 'column',
marginRight: 130,
marginBottom: 50
},
title: {
text: 'Top 12 Projects Facilities Rating and BSP Costs ',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: jsobj[0].data
},
yAxis: {
min: 0,
title: {
text: 'Facilities Rating'
},
plotLines: [{
value: 0,
width:1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
plotOptions:{
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color:'white'
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
borderWidth: 0,
x: -10,
y:110
},
series: [ {
name:'Facilities Rating',
data:firstSeriesData,
id:'dataseries'
},{
name:'BSP',
type:'spline',
data:secondSeriesData
}]
})
});
A couple comments.. your JSON had an unidentified character in it. This is what I got from pasting your JSON string.
Notice that red dot in the middle of the JSON.
Also, make sure you load highcharts modules in this order...
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
And lastly, you have two series in there, but one of them has values below 100 and the other one has values over 100k. So the first series is not gonna show as it almost 0 compared to the second. You'll have to do something about that.
In your function $.getJSON("combochart.php", function(json) you need to explicitly define what options you want. You are also not acutally setting any data. I am assuming that json[0]['data'] is a list of categories like ['Cat1', 'Cat2',...] and that json[1] and json[2] contain the data like [val1, val2, ...]. If so you need to do something like this:
$.getJSON("combochart.php", function(json) {
var theChart = $('#container').highcharts();
theChart.xAxis[0].setCategories(json[0]['data']); /*error here: ReferenceError: options is not defined */
theChart.series[0].setData(json[1]);
theChart.series[1].setData(json[2]);
//chart = new Highcharts.Chart(options);
});
});

Highcharts bargraph from json data in angularJS

I have a highcharts bargraph whose values are received from json whose format is as follows:
"bargraph":
[
{
"categories": "['S', 'M', 'T', 'W', 'T', 'F']",
"series1": "[800, 1100, 80, 1800, 1600, 2000]",
"series2": "[800, 1100, 80, 1800, 1200, 800]"
}
]
How can i embed those values for my bargraph in angularJS
HTML Code:
<div id="bargraph" bargraph={{bargraph}}><\div>
Directive:
angular.module('example').directive('bargraph', function () {
element.highcharts({
xAxis: [
{
categories: [] //embed categories value here
},
series: [
{
name: 'series1',
data: [] //Embed series1 data here
},
{
name: 'series2',
data: [] //Embed series2 data here
}
]
})
})
Please provide a suitable way to embed the data from json.
Here is a directive i copied and pasted from my webapp it is how i render highcharts using a directive NOTE: not all of this directive is applicable to you and some of it is specific to what i needed but you get the idea.
lrApp.directive('chart', function () {
return {
restrict: 'E',
template: '<div></div>',
transclude: true,
replace: true,
link: function (scope, element, attrs) {
var chart = null;
var chartsDefaults = {
chart: {
renderTo: element[0],
type: attrs.type || null,
height: attrs.height || null,
width: attrs.width || null,
},
colors: scope.$eval(attrs.colors) || null,
title: {
style: {
display: 'none'
}
},
xAxis: {
//categories: ['{"-7 days"|date_format}','{"-6 days"|date_format}','{"-5 days"|date_format}','{"-4 days"|date_format}', '{"-3 days"|date_format}', '{"-2 days"|date_format}', '{"-1 day"|date_format}', '{$smarty.now|date_format}'],
categories: scope.$eval(attrs.dates) || null,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1,
labels: {
y: 27
}
},
yAxis: {
title: {
text: null
},
min: 0,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1
},
credits: {
enabled: false
},
legend: {
enabled: false
},
plotOptions: {
series: {
shadow: false,
lineWidth: 3
}
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.x + ': ' + this.y + '</b>';
}
}
};
//Update when charts data changes
scope.$watch(attrs.value, function (newVal, oldVal) {
if (!newVal.length) return;
// We need deep copy in order to NOT override original chart object.
// This allows us to override chart data member and still the keep
// our original renderTo will be the same
var deepCopy = true;
var newSettings = {};
chartsDefaults.series = newVal;
chartsDefaults.colors = scope.$eval(attrs.colors);
chartsDefaults.xAxis.categories = scope.$eval(attrs.dates);
console.log(chartsDefaults);
chart = new Highcharts.Chart(chartsDefaults);
});
}
}
});
and this is how it used it obviously you would change "line" to bar:
<chart value="stats.sets" dates="stats.days" colors="stats.colors" type="line"></chart>

Multiple series from JSON Highstock

I have a problem with my HighStock, I need another series from JSON.
My code in get_json.php
include('config.php');
$cp = $_REQUEST["c_prot"];
$r=("SELECT * FROM data WHERE cp='$cp'");
$result=mysql_query($r);
while($row = mysql_fetch_array($result)){
$date= strtotime($row['cas'])*1000; // timestamp
$values=hexdec($row['data']); // series1
$val=hexdec($row['src']); // series2
$array[]=array($date, $values,$val); //output array
}
echo json_encode($array);
JSON output is in correct format: [1364852734000, 557, 2884],....
But problem is, that I didn't find how to add second series from JSON to Highstock code
I would like to display in chart x-axis: timestamp
y-axis: series1->data
series2->src
chart now displays only on x-axis timestamp and on y-axis data...but series2 doesn't work:/
High Stock code:
<script>
$(function () {
$.getJSON('http://localhost/vojto/get_json.php?c_prot=<?=$_REQUEST['
c_prot '];?>', function (data) {
// Create the chart
$('#container').highcharts('StockChart', {
chart: { //zooming
zoomType: 'x',
height: 400,
},
legend: { //legenda
enabled: true,
align: 'left',
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderWidth: 1,
layout: 'vertical',
verticalAlign: 'top',
y: 100,
shadow: true
},
rangeSelector: { //range selector
buttonTheme: {
width: 40,
},
buttonSpacing: 3, //mezera mezi buttony
enabled: true,
buttons: [{
type: 'minute',
count: 60,
text: 'Hour'
}, {
type: 'day',
count: 1,
text: 'Day'
}, {
type: 'week',
count: 1,
text: 'Week'
}, {
type: 'all',
text: 'Reset'
}]
},
title: { //title grafu
text: 'Chart'
},
series: [{ //serie
name: 'Data',
data: data,
color: '#57c72f',
marker: {
enabled: true,
radius: 3
},
shadow: true,
tooltip: {
valueDecimals: 2
}
}],
xAxis: { // X-osa
type: 'datetime',
title: {
text: 'Date/time axis',
},
minRange: 600000,
},
yAxis: {
min: 0,
},
navigator: {
series: {
color: '#57c72f',
fillOpacity: 0.3,
}
},
credits: {
enabled: false
},
tooltip: { // formátování hodnot po najetí kurzoru... hover
formatter: function () {
var s = '<b>' + Highcharts.dateFormat('DateTime ' + '%d-%m-%y ' + '%H:%M:%S', this.x) + '</b>';
$.each(this.points, function (i, point) {
s += '<br/>Data value : ' + point.y;
});
/* formát 23-04-13 09:34:27 */
return s;
}
},
});
});
});
</script>
In you script:
$array = [];
while($row = mysql_fetch_array($result)){
$date= strtotime($row['cas'])*1000; // timestamp
$values=hexdec($row['data']); // series1
$val=hexdec($row['src']); // series2
$array[0][]=array($date, $values); //output array
$array[1][]=array($date ,$val);
}
You need paste values to appropriate series index. In other words you can prepare your $array() and add point to one of series. To be honest I have no data so It is only concept.

Add multiple series from json file to highcharts

Please help,
I have only known about highcharts, Json and Jquery for 5 days. I have a Json file with info about 3 sets of results. I am trying to put 3 different lines on a highcharts chart. I do not know the syntax for this. i know that calling the options object allows you to add series and categories. I do not know the syntax to accomplish this
Here is the code so far:
var chart;
var eng_data;
var data;
var options, series;
$(document).ready(function () {
options = {
chart: {
renderTo: 'container',
zoomType: 'x',
spacingRight: 20
// events: { load: requestData }
},
title: {
text: null
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' :
'Drag your finger over the plot to zoom in'
},
xAxis: {
type: 'datetime',
maxZoom: 7 * 24 * 3600000, // 7 days
title: {
text: null
}
},
yAxis: {
title: {
text: 'Percentages'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
plotOptions: {
area: {
fillColor: {
linearGradient: [0, 0, 0, 300],
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, 'rgba(2,0,0,0)']
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 2
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
}
}
},
series: []
};
});
$.getJSON('eng.txt', function (eng_data) {
for (var i = 0; i < eng_data.length; i++) {
series = {
data: []
};
if (i == 1 && i <= 4) {
// options.addSeries({
data: eng_data[i];
name: "English";
pointInterval: 72 * 3600 * 1000;
pointStart: Date.UTC(2012, 0, 01)
// });
}
if (i == 5 && i <= 8) {
// options.addSeries({
data: eng_data[i];
name: "Maths";
pointInterval: 72 * 3600 * 1000;
pointStart: Date.UTC(2012, 0, 02)
// });
}
if (i == 9 && i <= 12) {
// options.addSeries({
data: eng_data[i];
name: "Science";
pointInterval: 72 * 3600 * 1000;
pointStart: Date.UTC(2012, 0, 03)
// });
}
options.series.push(series);
var chart = new Highcharts.Chart(options);
}
});