I'm trying to create a Pie Graph with High charts. I get all the values from the database through PHP, as well as the series, which are send to jQuery through JSON in which I parse that JSON and get it to the function that creates the graph.
$query = [array('name'=>'SAP', 'id'=>48), array('name'=>'EIS', 'id'=>65), array('name'=>'P2P', 'id'=>84), array('name'=>'Portal Gift Card', 'id'=>92), array('name'=>'Tenants Survey', 'id'=>74), array('name'=>'Outros', 'id'=>17)];
$series = array('name' => 'Effort');
$seriesData = array();
foreach ($query as $data){
$rslt = $this->gm->getEffortApp($data['id']);
array_push($seriesData, array('name' => $data['name'], 'y' => $rslt));
}
$series['data'] = $seriesData;
echo json_encode($series, JSON_NUMERIC_CHECK);
This are the codes that get me the data and send it to the jQuery through JSON.
$(document).ready(function(){
var param = '<?=$graphdata['param']?>';
asyncCall('post', '?/graphAsync/getSeries/'+<?=$graphdata['graph_id']?>,{param: param}, 'text',function(data){ //returns the right array to populate the graph
var series = $.parseJSON(data);
setChartData($('#graph'+<?=$graphdata['id']?>), '<?=$graphdata['graph_type']?>', '<?=$graphdata['graph_title']?>', 'Teste', '<?=$graphdata['graph_titleY']?>', series);
});
});
This is the code that receives all the graph data and parses the JSON string.
function setChartData(elem, type, title, categories, titleY, series){
elem.highcharts({
chart: {
type: type
},
title: {
text: title
},
xAxis: {
categories: categories
},
yAxis: {
min: 0,
title: {
text: titleY
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.textColor) || 'white',
style: {
textShadow: '0 0 3px black'
}
}
},
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: series,
credits: {
enabled: false
}
});
}
This is the function that creates the graph.
The rest of the graph data comes from the controller load (CodeIgniter) and seems to be fine.
The output of the server (JSON string) is as follows:
[{"name":"SAP","y":9420.35},{"name":"EIS","y":2282.5},{"name":"P2P","y":218.5},{"name":"Portal Gift Card","y":203},{"name":"Tenants Survey","y":323},{"name":"Outros","y":1}]
And the input in the function of the series is something like this:
series=[object,object,object,object,object,object]
And each object is as follows:
object:[name:'something', y:*number*]
The graph loads empty, only with the title and the export button.
For some reason I can't post images so that's why I didn't put any image of the graph output.
thanks in advance.
EDIT: here is the jsfiddle, although for some reason I can't get it to work the way it is in localhost. That's essentially what I'm doing, but instead i'm passing the arguments through PHP variables.
Related
I'm using html, css and javascript for the project. The server is set up locally including node, express and highcharts.
In my html i have a div container, that i'm referencing in my highcharts function. The data i'm using in the highchart come from a csv file. I wrote a simple getData function, that parses the data into an array. And at the top of the highchartsfunction, i'm using await getData, so the chart can only be rendered after getting the data for it. All functions are async. On that one page i'm having seven charts, all constructed using the syntax following below, each with its own getData function and div container.
Two problems:
Problem No.1:
The charts are not getting displayed until i refresh the page and often times i even have to refresh it several times, till every chart is getting shown at a time (Like 20 times). The functions are all executed, i checked that in the console.
Problem No.2:
I would like to write this dynamically, as i want to have multiple pages on my website, each using its own csv file, but basically the same code.
*Edit:
From time to time i receive: "Error: Highcharts error #13: www.highcharts.com/errors/13/" in the console, but as i keep refreshing it changes the line/js it is referencing to. It always is the part of the highcharts function, in which i give it its container Highcharts.chart('hammerchart', {. I checked this error and what it sais is basically, that the script can't find a container with the #id. Which i don't understand as im using "DOMContentLoaded". I tried the "load" event instead, which solved the error #13, but ended up in no chart getting displayed at all without any error message.
*Edit2:
Until now i only used firefox to view my website. I checked Chrome aswell and here i don't have any error message, but it also never shows any of the charts aswell at all.
If someone could help me out here, i would be really happy, as i tried to fix this for days now with no success. I'm also open for suggestions, regarding the handling of my data. Thank you veeeery much in advance!!
Code:
CSV Data sample
2015,2.5,7.2,1.6,6.5,2.2
2016,3.5,7.6,2.6,9.3,1.2
2017,2.5,7.2,1.6,6.5,2.2
2018,3.5,7.6,2.6,9.3,1.2
2019,2.5,7.2,1.6,6.5,2.2
HTML
<div id="hammerchart">
</div>
CSS
#hammerchart{
width:49%;
height: 500px;
margin:0.5%;
margin-top:50px;
flex: 1 1 600px;
}
Javascript - first declaration of the arrays, then my parsing function, splitting the csv by linebreaks and commas. Then i'm using parseFloat(), so that i don't have strings in it. In the highcharts function i'm using await getData and DOMContentloaded, to make sure both html and my data are ready.
const years = [];
const columntwos = [];
const columnthrees = [];
const columnfours = [];
const columnfives = [];
const columnsixs = [];
async function getDataone() {
const response = await fetch('/javascripts/hammerchart.CSV');
const data = await response.text();
const table = data.split('\n');
table.forEach(row => {
const columns = row.split(',');
const year = columns[0];
years.push(year);
const columntwo = columns[1];
columntwos.push(parseFloat(columntwo));
const columnthree = columns[2];
columnthrees.push(parseFloat(columnthree));
const columnfour = columns[3];
columnfours.push(parseFloat(columnfour));
const columnfive = columns[4];
columnfives.push(parseFloat(columnfive));
const columnsix = columns[5];
columnsixs.push(parseFloat(columnsix));
});
};
async function hammerchart() {
await getDataone();
document.addEventListener('DOMContentLoaded', () => {
Highcharts.chart('hammerchart', {
chart: {
zoomType: 'xy'
},
title: {
text: 'Data'
},
subtitle: {
text: ''
},
credits: {
text: 'highcharts',
},
xAxis: [{
categories: years,
plotBands: [{ // visualize
from: 4.5,
to: 6,
color: 'rgba(68, 170, 213, .2)'
}],
crosshair: true
}],
yAxis: [{ // Primary yAxis
labels: {
format: '{value}$',
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'Amount in $',
style: {
color: Highcharts.getOptions().colors[1]
}
}
}, { // Secondary yAxis
title: {
text: 'Ratio in %',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} %',
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.defaultOptions.legend.backgroundColor || // theme
'rgba(255,255,255,0.25)'
},
series: [{
name: 'columntwo',
type: 'areaspline',
data: columntwos,
tooltip: {
valueSuffix: '$'
}
}, {
name: 'columnthree',
type: 'areaspline',
data: columnthrees,
tooltip: {
valueSuffix: '$'
}
}, {
name: 'columnfour',
type: 'areaspline',
data: columnfours,
tooltip: {
valueSuffix: '$'
}
}, {
name: 'columnfive',
type: 'column',
data: columnfives,
tooltip: {
valueSuffix: '$'
}
}, {
name: 'columnsix',
type: 'spline',
yAxis: 1,
data: columnsixs,
tooltip: {
valueSuffix: '%'
}
}]
});
});
};
hammerchart();
I have a Highchart graph which receives data from backend in the form of Handlebars expressions. Something like this.
$('#container').highcharts({
xAxis: {
categories: [{{{histKeys}}}]
},
yAxis: {
title: {
text: 'Failure Percentage',
style: {
color: '#cc0000'
}
},
labels: {
format: '{value}%',
style: {
color: '#cc0000'
}
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
credits: {
enabled: false
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
var index = this.series.name;
var tfs = epochKeys[Math.ceil(this.x)];
window.location.href = url;
return false;
}
}
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [
{{#each histData as |index|}}
{
name: '{{#key}}',
type: 'spline',
allowPointSelect: true,
{{#each index as |status|}}
{{#if_eq #key "histSuccess"}}
{{/if_eq}}
{{#if_eq #key "histFailure"}}
data: [{{this}}],
{{/if_eq}}
{{/each}}
},
{{/each}}
]
});
Now i make an AJAX call to get data to refresh the graph. How do i pass the new value of Handlebars expressions to the variables used in the Highcharts code.
So the data i receive in the AJAX call contains the values of all these expressions that have been used in the Highcharts function.
Since the code is dynamic, i can't manually update the series values also because the number of lines on the graph differ depending upon the data coming from the backend.
Thanks for any input.
You can get the (already existing) highcharts object in the ajax callback like this:
$('#container').highcharts()
There's in fact a quite good API to interact with this object, documented here: http://api.highcharts.com/highcharts
For starters, you can replace an existing chart by calling addSeries() again. For that to work, your series must have an id, and you add a series with the same id again:
$('#container').highcharts().addSeries({ id: 'myid', data: .... });
In the same way, you can also remove existing series:
$('#container').highcharts().removeSeries('myid');
It's also possible only to replace the data of a series, something along the lines of this:
$('#container').highcharts().getSeries('myid').setData(...);
I hope that is a little help for you.
I am trying to customize stacked column chart like this
Here i did all the remaining things but i Don't know how to give that bar lines above every column........I need that bar lines in both positive and negative axis
My code
$(document).ready(function () {
$('#div1').highcharts({
chart: { type: 'column', backgroundColor: 'transparent' },
title: { text: null },
subtitle: { text: null },
credits: {
enabled: false
},
xAxis: {
categories: categories,
labels: {
rotation: 0,
style: {
fontWeight: 'normal',
fontSize: '0.9vw',
fontFamily: 'Verdana, sans-serif',
color: "black"
}
}
},
yAxis: {
title: {
enabled: false
},
lineWidth: 0,
gridLineWidth: 1,
labels: {
enabled: true
},
// gridLineColor: 'transparent',
plotLines: [{
color: '#ddd',
width: 1,
value: 0
}],
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series:seriesforSeniorUPT
});
});
});
Link
Fiddle
To elaborate on Sebastian Bochan's helpful comment, here's an updated version of your fiddle with two "dummy" series to serve as the patterned background: https://jsfiddle.net/brightmatrix/hc8rLy18/2/
A few items to note:
There are two "dummy" series: one for the positive numbers and one for the negative numbers.
Both series have showInLegend and enableMouseTracking set to false so the user cannot interact with them.
Both series have stacking set to false so they will not be part of the "real" data you want to show.
Both series have zIndex set to 0. I explain why below the code block.
The code for the "dummy" series is as follows.
// background for positive values
obj = {};
obj["name"] = 'patternFill';
obj["data"] = [120, 120];
obj["color"] = 'url(#highcharts-default-pattern-3)';
obj["grouping"] = false;
obj["zIndex"] = 0;
obj["enableMouseTracking"] = false;
obj["stacking"] = false;
obj["showInLegend"] = false;
seriesforSeniorUPT.push(obj);
// background for negative values
obj = {};
obj["name"] = 'patternFill';
obj["data"] = [-80, -80];
obj["color"] = 'url(#highcharts-default-pattern-3)';
obj["grouping"] = false;
obj["zIndex"] = 0;
obj["enableMouseTracking"] = false;
obj["stacking"] = false;
obj["showInLegend"] = false;
seriesforSeniorUPT.push(obj);
For the three "real" data series, I set zIndex to 10 to they will appear over the "dummy" series we're using for our patterend backgrounds.
For all of the series, I set grouping to false so they will appear one atop the other, not next to one another.
Here's a screenshot of the output. I hope this is helpful!
I am making a pie chart with json data but pie chart is not coming with data backend data.I am generating the data with this format which is actually the format given by HighCharts.I am pasting my code
function createChart(array){
//alert(array);
var arrJobName = [];
var arrRevenue = [];
for(var i=0; i<array.length; i++){
searchResultArray = array[i].split("$$##$$##");
//var label = '\''+ searchResultArray[1]+ '\'';
//var value = parseInt(searchResultArray[5]);
//arrJobName.push(searchResultArray[1]);
//arrRevenue.push(parseInt(searchResultArray[5]));
//alert(parseFloat(searchResultArray[5]))
// arrRevenue.push(['\''+ searchResultArray[1]+ '\'',""(parseFloat(searchResultArray[5]))]);
arrRevenue.push('['+searchResultArray[1]+","+parseFloat(searchResultArray[5])+']');
}
alert(arrRevenue)
//
$(function () {
$('.containerForDiagram').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2014'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Job By Revenue',
data: [
[arrRevenue]
//['Director - Inventory/Planning Systems',36800],['DevOps Engineer',20000], ['Java Developer',0],['Software Development Manager',0],['Sr. Business Analyst / Oracle Functional',0],['Product Manager Native Advertising',0],['Corporate Recruiter ',26000],['Sr. Oracle Supply Chain BA',0],['Network Engineer',0],['Sharepoint Programmer Analyst',0],['Commercial Manager - Mexico',0],['Commercial Manager Colombia',0],['Sr. Global Architect - End User Computing',29900],['Head of Marketing Peru',0],['Director, Sr Attorney',0]
this is the data i am getting with my code ]
}]
});
});
}
The data i am getting for the arrRevenue is given here.But the arrRevenue is not working when i am using it dynamically.I have tried all syntax.But no use still .Somebody please help.
The problem is with generating data. Required are two changes:
data assignment: data: [arrRevenue] -> data: arrRevenue
data generation: arrRevenue.push('['+searchResultArray[1]+","+parseFloat(searchResultArray[5])+']'); -> arrRevenue.push( [ searchResultArray[1], parseFloat(searchResultArray[5]) ] );
I write because I go back to being stuck in a problem with Highcharts. I have a monthly chart that works fine except for one thing. The zoom level. The X axis is always shown me a value of 0 (today), so that the zoom level is incorrect. I am attaching a picture to try to explain it better. I need this column set in the graph.
I appreciate your help! Thank you!
The json returned by PHP is (correct results):
{"data":[[1401580800000,2],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0],[1400025600000,0]]}
And Javascript file:
chart = new Highcharts.Chart({
chart: {
renderTo: 'divStatsGrupo',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: tituloMes
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%d/%m/%Y',new Date(this.x)) + '<br/>' +'Alarmas: ' + this.y
}
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats : {
day: '%e. %b',
labels: {
style: {
width: '200px','min-width': '100px'
},
useHTML : true,
}
}
},
yAxis: {
title: {
text: 'Total alarmas'
},
allowDecimals: false,
min: 0
},
series : [{
showInLegend: false,
name : 'Grafica Mensual',
type : 'column',
data: data.data,
dataLabels: {
enabled: true,
rotation: 0,
color: '#000000',
align: 'center',
y: 0,
style: {
fontSize: '14px',
fontFamily: 'Verdana, sans-serif',
}}
}]
});
}); ///cierra get
EDIT: I need a graphic for month (user select), but, the white area and Xaxis only appers info for the month selected. The PHP file return a correct JSON chain, but highcharts not fit the columns fine. Sorry for my english!
The problem is with your JSON, where you have duplicated values for the same timestamp. Just remove them.
Then! You have unsorted data, it should be sorted ascending by timestamp.
After fixed, it works fine, see: http://jsfiddle.net/4nCx3/
var data = {
"data": [
[1400025600000, 0],
[1401580800000, 2]
]
};