Highcharts combination chart from JSON data - javascript

I am creating a combination chart taking data from a database. I am able to import all the data and render it in single type i.e. Column. There is one series though which I want to render in spline type. The tutorial I am following only teaches about rendering in a single type, so I am kind of lost here.
This is my JavaScript
$(document).ready(function(){
var options = {
chart: {
renderTo: 'fetch-render',
type: 'column',
},
xAxis: {
title: {
text: 'Date'
},
categories: []
},
yAxis: {
title: {
text: 'Number'
},
series: []
}
$.getJSON("includes/fetch-data.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
/*so on...... */
options.series[7] = json[8];
/* i want to draw this series in spline */
options.series[8] = json[9];
chart = new Highcharts.Chart(options);
});
})
I want to draw data from series 8 as a spline unlike others which are drawn in column type

Highcharts Demos have all kinds of demos of using Highcharts. One of them shows how to draw different types of series in the same chart: http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/combo/
Basically, instead of defining the type on the chart object like you did, you will set the type for each series on your series object:
series: [{
type: 'column',
name: 'Jane',
data: [3, 2, 1, 3, 4]
}, {
type: 'column',
name: 'John',
data: [2, 3, 5, 7, 6]
}, {
type: 'column',
name: 'Joe',
data: [4, 3, 3, 9, 0]
}, {
type: 'spline',
name: 'Average',
data: [3, 2.67, 3, 6.33, 3.33],
marker: {
lineWidth: 2,
lineColor: Highcharts.getOptions().colors[3],
fillColor: 'white'
}
}

Thanks for the heads up by #João Menighin . i adopted the method given in this demo. its neater, cleaner and can be used to add as many chart types as needed. here is the code for someone else who wants to make a combined chart taking data from the database.
$(document).ready(function(){
$.getJSON("includes/fetch-data.php", function(json){
Highcharts.chart('fetch-render', {
title: {
text: 'Fetched Data'
},
xAxis: {
categories: json[0]['data']
},
series: [{
type: json[1]['type'],
name: json[1]['name'],
data: json[1]['data']
}, {
type: json[2]['type'],
name: json[2]['name'],
data: json[2]['data']
}, {
type: json[3]['type'],
name: json[3]['name'],
data: json[3]['data']
},{
type: json[4]['type'],
name: json[4]['name'],
data: json[4]['data']
}, {
type: json[5]['type'],
name: json[5]['name'],
data: json[5]['data']
}, {
type: json[6]['type'],
name: json[6]['name'],
data: json[6]['data']
}, {
type: json[7]['type'],
name: json[7]['name'],
data: json[7]['data']
},{
type: json[8]['type'],
name: json[8]['name'],
data: json[8]['data']
},{
type: json[9]['type'],
name: json[9]['name'],
data: json[9]['data']
}],
});
})
})
And i have set the chart types in fetch-data.php like this
$date = array();
$date['name'] = 'Date';
$blank=array();
$blank['name'] = 'Blank';
$blank['type'] = 'column';
$direct=array();
$direct['name'] = 'Direct';
$direct['type'] = 'area';
$checked_in=array();
$checked_in['name'] = 'Checked In';
$checked_in['type'] = 'column';
$conf=array();
$conf['name'] = 'Conf';
$conf['type'] = 'column';
$gdf=array();
$gdf['name'] = 'GDF';
$gdf['type'] = 'column';
$gdp=array();
$gdp['name'] = 'GDP';
$gdp['type'] = 'column';
$gtn=array();
$gtn['name'] = 'GTN';
$gtn['type'] = 'column';
$prov=array();
$prov['name'] = 'PROV';
$prov['type'] = 'column';
$enquire=array();
$enquire['name'] = 'ENQUIRE';
$enquire['type'] = 'spline';

Related

Reduce the number of lines

I have defined two charts below for example. But I use more than 50 charts in my code.
The difference between both charts are: chartNumber, containerNumber, id, text and data. Also the condition that is used for checking each chart at the beginning.
Working fiddle of the same: https://jsfiddle.net/2s93zb4j/12/ (pls check all 3 charts to view all of them)
Instead of repeating same lines of code for each chart, will I be able to reduce the number of lines using for loop or forEach. Thank you.
//Chart1
if (checkNA=== "NA")
chart0 = Highcharts.chart('container1', {
id: 1,
yAxis: [{
title: {
text: 'NorthAmerica'
}
}],
series: [{
data: NorthAmericaData,
type: 'line',
}],
});
}
//Chart2
if (checkSA=== "SA")
chart1 = Highcharts.chart('container2', {
id: 2,
yAxis: [{
title: {
text: 'SouthAmerica'
}
}],
series: [{
data: SouthAmericaDta,
type: 'line',
}],
});
}
A class would go a long way here.
class ChartObject {
constructor(id, text, data) {
this.id = id;
this.yAxis = [
{
title: {
text,
},
},
];
this.series = [
{
data,
type: 'line',
},
];
}
}
//Chart1
if (checkNA === 'NA') {
chart0 = Highcharts.chart(
'container1',
new ChartObject(1, 'NorthAmerica', NorthAmericaData)
);
}
//Chart2
if (checkSA === 'SA') {
chart1 = Highcharts.chart(
'container2',
new ChartObject(2, 'SouthAmerica', SouthAmericaDta)
);
}
Hope this helps.

How to display grouped data in ChartJs

I have the following array:
Where the arrays keys are the dates and the only element I want to plot, of each set, is the weight. Look:
I am putting the code as follows. Notice that I am already grouping in the date attribute the whole set belonging to each that key.
var ctx = document.getElementById("barChart").getContext("2d");
var data = {
labels: ['21/03/2018','01/04/2018','02/04/2018','04/04/2018','05/04/2018','06/04/2018'],
datasets: [
{
label: '21/03/2018',
data: [12, 0, 0]
},
{
label: '01/04/2018',
data: [15.00, 15.00,15.00]
},
{
label: '02/04/2018',
data: [25.00, 25.00, 25.00]
},
{
label: '04/04/2018',
data: [25.00, 25.00, 25.00]
},
{
label: '05/04/2018',
data: [-8.14,-7.93, -7.84]
},
{
label: '06/04/2018',
data: [-35.9 ,-38.1, -37.5]
},
]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
});
But in this way ChartJs does not understand that it only needs to plot the data set present in the "data" attribute and grouping them by the key. Plotting the graph in the wrong way.
How could I plot the data correctly knowing that they are already grouped?
You need to organize your data as such:
var ctx = document.getElementById("canvas").getContext("2d");
var data = {
labels: ['21/03/2018','01/04/2018','02/04/2018','04/04/2018','05/04/2018','06/04/2018'],
datasets: [
{
data: [12, 15.00, 25.00, 25.00, -8.14, -35.9]
},{
data: [0, 15.00, 25.00, 25.00, -7.93, -38.1]
},{
data: [0, 15.00, 25.00, 25.00, -7.84, -37.5]
}
]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options:{
legend: 'none'
}
});
I took your legend out as it's useless in this case. To look at it in the coding persepective, whatever index the date in labels is at needs to correlate with the index of the information you want to display in that grouping. data[0] refers to labels[0] and so on.

execute jquery function when data-ajax=“true”

I have a mobile app developed using jquery mobile. One one page i have a chart. When the user clicks on <a href="chart.html" data-ajax=“true”>Chart</a> the page loads but the chart doesnt load. When i refresh the page the chart works.
When data-ajax=“false” the page works but its not smooth and doest have the transition effects
Below is my chart code
<script type="text/javascript">
$(function () {
var limit = 10000; //increase number of dataPoints by increasing the limit
var y = 0;
var data = [];
var dataSeries = { type: "line" };
var dataPoints = [];
for (var i = 0; i < limit; i += 1) {
y += (Math.random() * 10 - 5);
dataPoints.push({
x: i,
y: y
});
}
dataSeries.dataPoints = dataPoints;
data.push(dataSeries);
//Better to construct options first and then pass it as a parameter
var options = {
zoomEnabled: true,
animationEnabled: true,
title: {
text: "Try Zooming - Panning"
},
axisX: {
labelAngle: 30
},
axisY: {
includeZero: false
},
data: data // random data
};
$("#chartContainer").CanvasJSChart(options);
});
</script>
HTML
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
Is there away to execute the chart function without setting data-ajax=“false” ?
To work with complicated charts, i usually use Highcharts, it is very responsive and very customizable, and it also have very smooth transition effect when it shows.
Here is a Example on JSFiddle.
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Column chart with negative values'
},
xAxis: {
categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
},
credits: {
enabled: false
},
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]
}]
});
I hope it help.

Highchart: add href to each segment of stacked bar chart

I want to put specific link on each segment of stacked 100% bar chart..
Demo of stacked bar chart : http://www.highcharts.com/demo/bar-stacked
In details what I am doing and what I am looking for is : Please go to http://barchart.worddss.com/new/ and fill data in left table and submit.
After submit, As you can see each different color segment have a different url but url is like : http://barchart.worddss.com/new/url2&value=2
i.e. I can give fixed url to every fixed color segment and behind value of label..
But I want is, different urls to every segment.. like yellow to google.com , green to fb.com etc..
Code I am using is :
function show () { var m1=document.getElementById('m1').value;
var m2=document.getElementById('m2').value;
var m3=document.getElementById('m3').value;
var m4=document.getElementById('m4').value;
var m5=document.getElementById('m5').value;
var m6=document.getElementById('m6').value;
var m7=document.getElementById('m7').value;
var c1=document.getElementById('c1').value;
var c2=document.getElementById('c2').value;
var c3=document.getElementById('c3').value;
var c4=document.getElementById('c4').value;
var c5=document.getElementById('c5').value;
var c6=document.getElementById('c6').value;
var c7=document.getElementById('c7').value;
var e1=document.getElementById('e1').value;
var e2=document.getElementById('e2').value;
var e3=document.getElementById('e3').value;
var e4=document.getElementById('e4').value;
var e5=document.getElementById('e5').value;
var e6=document.getElementById('e6').value;
var e7=document.getElementById('e7').value;
var seriesData = [];
seriesData.push({
name: "Por cursar",
data: [parseFloat(e7),parseFloat(c7),parseFloat(m7)],
url: ["url1","egg","gfhf"]
});
seriesData.push({
name: "Acreditados",
data: [parseFloat(e6),parseFloat(c6),parseFloat(m6)],
url: "url1"
});
seriesData.push({
name: "Nivel 4",
data: [parseFloat(e5),parseFloat(c5),parseFloat(m5)],
url: "url1"
});
seriesData.push({
name: "Nivel 3",
data: [parseFloat(e4),parseFloat(c4),parseFloat(m4)],
url: "url1"
});
seriesData.push({
name: "Nivel 2",
data: [parseFloat(e3),parseFloat(c3),parseFloat(m3)],
url: "url1"
});
seriesData.push({
name: "Nivel 1",
data: [parseFloat(e2),parseFloat(c2),parseFloat(m2)],
url: "url1"
});
seriesData.push({
name: "Por acreditar",
data: [parseFloat(e1),parseFloat(c1),parseFloat(m1)],
url: "url2"
});
$('#container').highcharts({
chart: {
type: 'bar'
},
credits: {
enabled: false
},
title: {
text: "CURSO ACTUAL"
},
xAxis: {
allowDecimals: false,
categories: ['Español', 'Ciencias', 'Matematicas']
},
yAxis: {
min: 0,
allowDecimals: false,
title: {
text: ""
}
},
legend: {
backgroundColor: '#FFFFFF',
reversed: true
},
plotOptions: {
series: {
cursor: 'pointer',
stacking: 'percent',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px black'
}
},
point: {
events: {
click: function () {
window.location =(this.series.options.url + "&value=" + this.y);
// alert(this.series.options.url + "&y=" + this.y);
}
}
}
}
},
series: seriesData
});}
I am not completely sure if you want a url per color (serie) or per true segment (point). Thus I made a hybrid one.
Let's say for some series you need to have link per serie and for another link per point. The former looks more natural if URL is provided together with point value.
seriesData.push({
name: "Por cursar",
data: [{y:1, url:'http://facebook.com'}, {y:2, url:'http://google.com'}, {y:3, url: 'http://amazon.com'}]
});
seriesData.push({
name: "Acreditados",
data: [1, 2, 3],
url: "http://cnn.com"
});
This case you click handler must be
point: {
events: {
click: function () {
var point = this;
if (point.url) { //if url is per point as in Por cursar
window.open(point.url);
} else if (point.series.userOptions.url){ //if url is per serie as in Acreditados
window.open(point.series.userOptions.url);
}
}
}
}
Conplete sample can be found here http://plnkr.co/edit/j3NgoNWa6rwPgBGIJDwm

Change Highcharts Series color

EDIT:
So now I have a chart with all my data pushed off to the right, BUT I have labels in different colors for the sets I want to show but no data?? Updated my code
Original post:
I have a working highchart here http://opensourcesurf.com/chart.html . The problem is when I try and change the color of an individual data set, they all change. How could I change these settings given my code? Thanks in advance!
code:
var options1 = {
chart: {
renderTo: 'container1',
type: 'area'
},
xAxis: {
type: 'datetime'
},
series: [{
name: 'Swell Period',
color: '#0066FF',
data: 'newSeriesData',
},
{ name: ' Maximum Breaking Wave Height',
color: '#ffffff',
data: 'newSeriesData',
},
{ name: 'Swell Height',
color: '#123456',
data: 'newSeriesData',
}],
};
var drawChart = function(data, name, color) {
var newSeriesData = {
name: name,
data: data
};
// Add the new data to the series array
options1.series.push(newSeriesData);
// If you want to remove old series data, you can do that here too
// Render the chart
var chart = new Highcharts.Chart(options1);
};
$.getJSON('decode.php', function(data){
drawChart(data, 'Swell Height');
});
$.getJSON('decode2.php', function(data){
drawChart(data, ' Maximum Breaking Wave Height');
});
$.getJSON('decode3.php', function(data){
drawChart(data, 'Swell Period');
});
Try this:
// 'series' is an array of objects with keys:
// - 'name' (string)
// - 'data' (array)
// - 'color' (HTML color code)
var newSeriesData = {
name: name,
data: data,
color: color
};
The way to specify a color for a specific series is to define it when you're defining the series. For example:
series: [{
name: 'John',
color: '#0066FF',
dashStyle: 'ShortDash',
data: [
[Date.UTC(2010, 0, 1), 29.9],
[Date.UTC(2010, 2, 1), 71.5],
[Date.UTC(2010, 3, 1), 106.4]
]
},
So essentially when you're creating your series in your drawchart function, do a check for the name, and appropriately assign a color:
var color;
if(name=="Swell Height"){
color="#0066FF";
}else if(name=="Maximum Breaking Wave Height"){
color="#0066EE";
}else if(name=="Swell Period"){
color="#0066HH";
}
var newSeriesData = {
name: name,
data: data,
color: color
};
It looks to me like you are not looping through the array of data and/or you only have one set of data in data.

Categories