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]) ] );
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 Pie Chart that gets its data from the file. In raw form, this is the data:
[{"name":"Dual","load":"20"},{"name":"Gas","load":"35"},{"name":"Other_Fossil_Fuels","load":"15"},{"name":"Nuclear","load":"12"},{"name":"Hydro","load":"8"},{"name":"Wind","load":"10"},{"name":"Other_Renwables","load":"10"}]
I am trying to make a method that formats this data correctly so that it can be used in the pie chart. However only the Names come through correctly, with all of the percentages set to 0. I have a feeling that it is because the raw data is saved as a String. But using parseInt() on the data before pushing doesn't help and the === check returns num. Here is the code i am trying to implement.
function setPieData(data){
var json = JSON.parse(data);
var fuelTypes = [{name: 'Dual',load:[]},
{name: 'Gas', load:[]},
{name: 'Other_Fossil_Fuels', load:[]},
{name: 'Nuclear', load: []},
{name: 'Hydro', load: []},
{name: 'Wind', load: []},
{name: 'Other_Renwables', load:[]}];
for(i=0; i < json.length; i++){
if(json[i].name == fuelTypes[i].name){
fuelTypes[i].load.push(parseInt(json[i].load));
}
if(fuelTypes[i].load === parseInt(fuelTypes[i].load, 10)){
alert("not num");
}else{
alert("num");
}
}
drawChart(fuelTypes);
}
function drawChart(stuff){
var globalDate = new Date();
var dMth = globalDate.getMonth() + 1;
var dDay = globalDate.getDate();
var dYr = globalDate.getFullYear();
var dStr = dMth + '/' + dDay + '/' + dYr;
title = "Real-time Fuel Mix " + dStr;
var seriesData= stuff;
Highcharts.setOptions({
colors: ['#C00000', '#FF0000', '#7F7F7F', '#FFC000', '#4F81BD', '#00B050', '#92D050']
});
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: title
},
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'
}
},
showInLegend: true
}
},
series: [{
name: "MI Power",
colorByPoint: true,
data: stuff
}]
create an Array and push your data like following
var dataPie =[];
var abc =your data //your json
$.each(abc,function(i,el)
{
dataPie.push({name :el.name,y: parseInt(el.load)});
});
use dataPie in your drawChart function.
see working fiddle here
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.
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]
]
};
I've been doing this script for a volunteering university-site job.
Please ignore all parameters apart from wattages and schools. Those are SQL result sets that have been converted to arrays using json_encode(). Result sets have Strings as values, I believe, so both wattages and schools should be arrays of strings.
What I want to do is input my own data for the pie graph, in this case mySeries, which I build/fill up at the start and put as data later.
function createPieChartGradient(data,title,xlabel,ylabel,type,step,div_id,wattages,schools){
var float_watt = new Array();
for(var index = 0; index < wattages.length; index++)
{
float_watt[index] = parseFloat(wattages[index]).toFixed(2);
}
var mySeries = []; //Hopefully this creates a [String, number] array that can be used as Data.
for (var i = 0; i < float_watt.length; i++) {
mySeries.push([schools[i], float_watt[i]]);
}
var options = {
chart: {
renderTo: 'graph',
zoomType: 'x',
defaultSeriesType: type
},
title: {
text: 'Consumption Percentage of IHU Schools, Last 7 days'
},
tooltip: {
//pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
xAxis: {
categories: [],
tickPixelInterval: 150,
// maxZoom: 20 * 1000,
title: {
style: {
fontSize: '14px'
},
text: xlabel
},
labels: {
rotation: -45,
step: step,
align: 'right'//,
// step: temp
}
},
yAxis: {
title: {
style: {
fontSize: '14px'
},
text: ylabel
},
labels: {
align: 'right',
formatter: function() {
return parseFloat(this.value).toFixed(2);
}
},
min: 0
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'center',
floating: true,
shadow: true
},
series: [{
type: 'pie',
name: 'Consumption Percentage',
data: mySeries //Problematic line.
}] //Faculty with the smallest wattage -> Green.
}; //end of var options{} //Next: -> Yellow.
//Last -> Red.
//Draw the chart.
var chart = new Highcharts.Chart(options); //TODO: Change colours.
document.write("FINISHED");
}
The thing is, the above won't work. Since I'm not using an environment (writing in notepad++ and testing on my apache web server, via the results) I have manually aliminated the problematic line to be data: mySeries.
Any idea why that is? Aren't they the same type of array, [String, number]?
Additionally, are there any environments that will help me debug javascript programs? I'm really at my wit's end with this situation and I'd very much prefer to have an IDE tell me what's wrong, or at least point me at the right direction.
You see where you are calling "toFixed"? Let's run a small experiment:
var wattages = [2.0, 3.0];
var float_watt = new Array();
for(var index = 0; index < wattages.length; index++)
{
float_watt[index] = parseFloat(wattages[index]).toFixed(2);
}
console.log(JSON.stringify(float_watt));
The output is not what you expect:
["2.00", "3.00"]
See how it got converted to a string? If you delete the "toFixed" and let your formatter do its job, things will go just fine.
EDIT
Here's how you fix your formatter:
plotOptions: {
pie: {
dataLabels: {
formatter: function() {
return parseFloat(this.y).toFixed(2);
}
}
}
},
The yLabels formatter is doing nothing for the pie.