Highcharts parsed drilldown not showing on page but does in console - javascript

I have set up a simple column chart in Highcharts 4 with jQuery 1.9.1 where I parse a CSV file. I get the normal page showing with the column chart, but when I click on a bar nothing happens. I actually do see the arrays being created in the console (IE11) and they appear to be just what I need, they are in the correct syntax and the IDs match.
The JS fiddle [was...://jsfiddle.net/tjxwty3y/ ... I have changed this in the edit at the bottom ] . I put an example of the CSV that I use, but do not know how to link an external one into the JS Fiddle. I have tried the examples with CSV/TSVs embedded in the code and they have worked, so I think it has to do with how I am pushing the data, hence the external reference.
The CSV is very simple. I have the 3 categories in the first column, their values for the front chart, followed by the IDs in the 3rd and finally the drilldown values in the 4th and 5th.
CSV looks like this
AREA,VALUE,TYPE,SHIFT1,SHIFT2
Blog1,50000,Blog1_Shift,5,6
Blog2,60000,Blog2_Shift,2,3
Blog3,40000,Blog3_Shift,7,8
I have looked at multiple posts (and some videos) where the CSV or TSV is within the JS Fiddle and on Highcharts website, but I completely am not seeing where I have gone wrong (and I know that I have).
Just in case, here is the raw data from js fiddle which has the libraries (I typically use Higcharts 4 and JQuery 1.11 but here I've modified some older code that used JQuery 1.9.1):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="http://code.highcharts.com/highcharts.js"></script>
<script type='text/javascript' src="http://code.highcharts.com/modules/data.js"></script>
<script type='text/javascript' src="http://code.highcharts.com/modules/drilldown.js"></script>
<style type='text/css'></style>
<script type='text/javascript'>
//<![CDATA[
$(window).load(function () {
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'My Title Here'
},
xAxis: {
categories: [],
name: []
},
yAxis: {
title: {
text: 'Value Here'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
y: 15,
borderWidth: 0,
itemStyle: {
color: '#333',
fontSize: '15px',
},
navigation: {
activeColor: '#3E576F',
animation: true,
arrowSize: 12,
inactiveColor: '#CCC',
style: {
fontWeight: 'bold',
color: '#333',
fontSize: '15px',
}
}
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
marker: {
lineWidth: 1
}
}
},
series: [],
drilldown: []
};
$.get("http://my/csv/notvalid/dev_drilldown4.csv", function (csvData) {
var lines = csvData.split('\n');
var series = {
data: [],
visible: true,
type: 'column',
colorByPoint: true,
drilldown: true
};
var drilldown = {
series: []
};
$.each(lines, function (lineNo, line) {
if (lineNo > 0 && lineNo < 4) {
var items = line.split(',');
var seriesname = String(items[0]); // this is the area
var area_cost = parseFloat(items[1]); // this is the data for the rollup
var drill_id = String(items[2]); // this will be the id of the drilldown
var shift_one_value = parseFloat(items[3]); // shift1 value
var shift_two_value = parseFloat(items[4]); // shift2 value
series.data.push({
name: seriesname,
y: area_cost,
drilldown: drill_id
});
drilldown.series.push({
id: drill_id,
data: [["shift1", shift_one_value],["shift2", shift_two_value]]
});
}
});
console.log(series.data);
console.log(drilldown.series);
options.series.push({ data: series.data });
options.drilldown.push({ series: drilldown.series });
var chart = new Highcharts.Chart(options);
});
});
});
</script>
</head>
<body>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
I appreciate any for help/advice.
Thanks
EDIT:
Now that I have added in Salman's and Pawell's edits, including adding in the CSV to the jsFiddle (see Pawell's jsFiddle for what it now looks like) I encountered an additional issue, but it is/was working now!
I realized I forgot the "name" of the series and added that in, adjusting the 'var series' and changing the 'series.data.push' to 'series.push' and watched the log as mentioned by Salman. Now nothing appears, but the console log appears to show the data with the names, ids and data, but no chart (and no error).
The js fiddle is: http://jsfiddle.net/5jzb8hzb/1/. Would you know why changing the 'series.data.push' caused the initial chart to not render?

As noticed by #Salman, there is a couple of issues:
first load Highcahrts then drilldown.js (issue only in jsFiddle)
you shouldn't push to the drilldown array, but assign created series
you have drilldown: [], while should be drilldown: {}
for series you have options.series.push({ data: series.data }), while simply use options.series.push(series) or options.series = [series]
Extra note: I suggest to check values if those are not NaN's - sometimes editors create extra empty new line at the end of the file.
After all fixes, here is fully working code: http://jsfiddle.net/tjxwty3y/7/
Minimized example:
var options = {
chart: {
renderTo: 'container'
},
series: [],
drilldown: {}
};
var csvData = document.getElementById("data").innerHTML; // like $.get()
var lines = csvData.split('\n');
var series = {
data: [],
visible: true,
type: 'column',
colorByPoint: true,
drilldown: true
};
var drilldown = {
series: []
};
// I know with the below I get an extra line so can deal with that when I get the rest of the data sorted
$.each(lines, function (lineNo, line) {
if (lineNo > 0 && lineNo < 4) {
var items = line.split(',');
var seriesname = String(items[0]); // this is the area name
var area_cost = parseFloat(items[1]); // this is the data for the area rollup
var drill_id = String(items[2]); // this will be the id of the drilldown
var shift_one_value = parseFloat(items[3]); // drilldown shift1 value
var shift_two_value = parseFloat(items[4]); // drilldown shift2 value
if(!isNaN(area_cost) && !isNaN(shift_one_value) && !isNaN(shift_two_value)) {
series.data.push({
name: seriesname,
y: area_cost,
drilldown: drill_id
});
drilldown.series.push({
id: drill_id,
data: [
["shift1", shift_one_value],
["shift2", shift_two_value]
]
});
}
}
});
options.series = [series];
options.drilldown = drilldown;
var chart = new Highcharts.Chart(options);

There is a bug in the code; if you log options you will detect it. drilldown configuration is supposed to have a series key. But in your case the key is inside drilldown[0]; probably because of using push function.
The code worked after I changed
options.drilldown.push({ series: drilldown.series });
to
options.drilldown.series = drilldown.series;
There was also another bug- drilldown library should be loaded after highcharts.
Edit: Updated fiddle: http://jsfiddle.net/dxann41x/1/

Related

Echart.js library for graphs (javascript) does not show data on page using xaxis type is time

I try to show temperature on a webapge (using Echarts.js) within 24 hours based on whole hours.
I have added a sample html.doc which i try.
Somehow it does not show the data.
Here is my example code:
The staqck-overflow editor keeps complaining that i had to add more details, please view the code.
That is full code.
<!DOCTYPE html><html><head>
<meta charset="utf-8">
<title>ECharts</title>
<!-- including ECharts file -->
<script src="http://echarts.baidu.com/dist/echarts.js"></script>
</head>
<body>
<!-- prepare a DOM container with width and height -->
<div id="main" style="width: 80%;height:400px;"></div>
<script type="text/javascript">
// based on prepared DOM, initialize echarts instance
var myChart = echarts.init(document.getElementById('main'));
var now = new Date(2019,10,7);
var nowPlusOneday = +now + 24*3600*1000-1;
var data =[];
data.push([new Date(2019,10,7,1,5),19]); data.push([new Date(2019,10,7,2,10),34]);
data.push([new Date(2019,10,7,3,9),12]); data.push([new Date(2019,10,7,4,11),16]);
data.push([new Date(2019,10,7,5,13),29]); data.push([new Date(2019,10,7,6,16),14]);
data.push([new Date(2019,10,7,7,45),18]);
// specify chart configuration item and data
var option = {
title: {
text: 'Temperatuur'
},
legend: {
orient: 'horizontal',
top: 'bottom',
left: 'right'
},
tooltip: {
trigger: 'axis'
},
xAxis: {
type: 'time',
min: now,
max: nowPlusOneday,
splitNumber: 12,
data: data.map(function (item) {
return item[0];
})
},
yAxis: {
min: 'dataMin',
max: 'dataMax',
type: 'value',
splitLine: {
show: true,
},
axisLabel: {
formatter: '{value} °C'
}
},
dataZoom: [{
startValue: '2001-06-06'
}, {
type: 'inside'
}],
series: {
name: 'Temperatuur',
type: 'line',
data: data.map(function (item)
{
return item[1];
}),
markLine: {
silent: false
}
}
// use configuration item and data specified to show chart
myChart.setOption(option);
</script></body></html>
This is my output:
output of html file
All help is welcome.
Thanks in advance.
Anand

Parsing CSV and then Using the Data to Build Highcharts Bar Chart

I want to create a bar chart visualization IN JS FIDDLE that will visualize 'Q1 / 18 (TTM) Annual Guest Value' and 'Days Between 1st and 2nd Visits' for each category of Consumer which is: ['1', '2', .....'29+']. The bar chart should look like this (the legend is covering the 1st category but I'll fix this):
I assume that the data is present already in a CSV that looks like:
I have an interface that will allow the user to import a CSV file. It is here:
// The event listener for the file upload
document.getElementById('txtFileUpload').addEventListener('change', upload, false);
// Method that checks that the browser supports the HTML5 File API
function browserSupportFileUpload() {
var isCompatible = false;
if (window.File && window.FileReader && window.FileList && window.Blob) {
isCompatible = true;
}
return isCompatible;
}
function upload(evt) {
if (!browserSupportFileUpload()) {
alert('The File APIs are not fully supported in this browser!');
} else {
var data = null;
var file = evt.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var csvData = event.target.result; //alert(csvData);
var data2 = csvData.split("\n"); //alert(data2);
var i;
for (i = 0; i < data2.length; ++i) {
// here's the data row separated by commas
alert(i+': '+data2[i]);
// call your ajax and submit this one row
// now wait for response
// if not error:
// advance progress bar, and number converted, etc in modal
// else:
// show error message
}
if (data2 && data2.length > 0) {
alert('Imported -' + data2.length + '- rows successfully!');
} else {
alert('No data to import!');
}
};
reader.onerror = function() {
alert('Unable to read ' + file.fileName);
};
}
}
<h1>File Upload Test</h1>
<p>
<div id="dvImportSegments" class="fileupload ">
<fieldset>
<legend>Select the CSV file to upload</legend>
<input type="file" name="File Upload" id="txtFileUpload" accept=".csv" />
</fieldset>
</div>
</p>
Then, I am using .get() to bring in the variable csvData (from a function in the above code) and then I will parse it using the function parseCSVData (the function is written below). Then, I will make the bar chart of the data. Here is my code for this part:
$.get(csvData, function (csvFile) { //retrieve csvData from other function above
var data = parseCSVData(csvFile);
//create the chart
Highcharts.chart('container', {
chart: {
type: 'bar'
},
title: {
text: null,
align: 'center',
verticalAlign: 'bottom',
},
xAxis: {
categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11-17', '18-28', '29+'],
title: {
text: 'Visits Per Customer (TTM)'
},
},
yAxis: {
min: 0,
gridLineWidth: 0,
minorGridLineWidth: 0,
title: {
text: 'Average Return Rate Overall: 64 Days',
y: 10
},
labels: {
overflow: 'justify'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.0f} </b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
bar: {
dataLabels: {
enabled: true,
}
}
},
legend: {
layout: 'horizontal',
align: 'right',
verticalAlign: 'top',
x: -25,
y: 5,
floating: true,
borderWidth: 1,
backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
shadow: true
},
credits: {
enabled: false
},
series: [{
name: 'Q1 / 18 (TTM) Annual Guest Value',
//data: 2nd column of CSV file
color: 'grey',
// label color
dataLabels: {
style: {
color: 'grey'
}
}
}, {
name: 'Days Between 1st and 2nd Visits',
//data: 3rd Column of CSV file
color: 'green',
// label color
dataLabels: {
style: {
color: 'green'
}
}
}]
})
})
function parseCSVData (csvFile){
//empty array for storing the chart data
var guestvalue_and_visits = []; //2nd and 3rd column extraction
var lines = csvFile.split("\n");
$.each(lines, function (lineNumber, line){
if(lineNumber != 0) { //skipping header lines
var fields = line.split(",");
var a = parseFloat(fields[1]); // this is guest value
var b = parseFloat(fields[2]); //this is days between visit
guestvalue_and_visits.push([a , b]);
}
})
return guestvalue_and_visits.reverse();
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>
My questions are:
What is the right form of the data that I need to parse? Is it var data2 = csvData.split("\n") OR is it var csvData = event.target.result?
Did I bring in the variable csvData (or data2 if this is the right one) in correctly in .get()? I am not an expert in Javascript but I am pretty sure that for instance the variable csvData is local to reader.onload = function(event){} so I would somehow need to access this local variable. How would I bring this correctly into .get()? Would simply writing .get(csvData, function (csvFile){ be okay?
Also, if you look at the 'data' property under 'series', I have left it blank because I do not know how to bring the data from the guestvalue_and_visits variable into the Highcharts code. (I did guestvalue_and_visits.push([a , b] because this is the form Highcharts accepts). I want to extract the 'a' and 'b' part from the data structure and put them in their corresponding 'data' property under 'series'. How would I do this?
Last but not least, bringing everything together how would I allow the interface to FIRST allow the user to upload a CSV file and THEN when it is uploaded, the interface will change to the Highcharts bar chart? Is there some sort of code I need to write to do this?
What is the right form of the data that I need to parse? Is it var
data2 = csvData.split("\n") OR is it var csvData =
event.target.result?
In your case I recommend you to separate the categories and series data in your CSV string parser, and return two different series with data included, just like that:
var parseCSV = function(csv) {
var lines = csv.split("\n").map(line => line.split(",")) // split string to lines
var categories = []
var series = [{
name: 'Q1 / 18 (TTM) Annual Guest Value',
color: 'grey',
data: [],
dataLabels: {
style: {
color: 'grey'
}
}
}, {
name: 'Days Between 1st and 2nd Visits',
color: 'green',
data: [],
dataLabels: {
style: {
color: 'green'
}
}
}]
// Parse every line of csv file.
lines.forEach((line, i) => {
if (i !== 0) {
var cat = line[0].slice(1, -1)
var p1 = parseFloat(line[1])
var p2 = parseFloat(line[2])
categories.push(cat)
series[0].data.push(p1)
series[1].data.push(p2)
}
})
// return the object with categories and series
return {
categories: categories,
series: series
}
}
Then just assign the categories, and series:
var parsedCSV = parseCSV(csv)
Highcharts.chart('container', {
xAxis: {
categories: parsedCSV.categories
},
series: parsedCSV.series
})
Did I bring in the variable csvData (or data2 if this is the right one) in correctly in .get()? I am not an expert in Javascript but I am pretty sure that for instance the variable csvData is local to reader.onload = function(event){} so I would somehow need to access this local variable. How would I bring this correctly into .get()? Would simply writing .get(csvData, function (csvFile){ be okay?
I don't see your whole project structure, but yes, the csvData and data2 variables scope is limited only to reader.onload function so, you can't call get() anywhere except this event function.
Last but not least, bringing everything together how would I allow the
interface to FIRST allow the user to upload a CSV file and THEN when
it is uploaded, the interface will change to the Highcharts bar chart?
Is there some sort of code I need to write to do this?
Actually, I think the process of generating the chart should look like that:
Generate an empty chart (or with some initial data)
Get CSV from file
Parse CSV you've got
When parsed just update the chart with new categories and whole series object using Chart.update() method.
API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#update
Live example with parsing data in correct way: http://jsfiddle.net/db0vsgmh/

Highcharts Map not rendering no errors

I am attempting to take the example produced by Highcharts here http://www.highcharts.com/maps/demo/color-axis and substitute the data loaded by the $.getJson with a local JSON file called 'testdata1.json'.
The code I've modified below produces no errors yet the map does not render. I think it's because the testdata1.json is loaded late, after the javascript is executed. If so, is there a better way I should be doing this -- perhaps waiting for the data to load before executing the JS file? I attempted to do this by placing a
$(document).ready(
in front of the function but it didn't work. Any thoughts are greatly appreciated, I think it's something relatively minor that is just escaping me.
Thank you.
$(function () {
// Map options
var options = {
chart : {
renderTo: '#map',
borderWidth : 1
},
title : {
text : 'US population density (/km²)'
},
legend: {
layout: 'horizontal',
borderWidth: 0,
backgroundColor: 'rgba(255,255,255,0.85)',
floating: true,
verticalAlign: 'top',
y: 25
},
mapNavigation: {
enabled: true
},
colorAxis: {
min: 1,
type: 'logarithmic',
minColor: '#EEEEFF',
maxColor: '#000022',
stops: [
[0, '#EFEFFF'],
[0.67, '#4444FF'],
[1, '#000022']
]
},
series : [{
animation: {
duration: 1000
},
mapData: Highcharts.maps['countries/us/us-all'],
joinBy: ['postal-code', 'code'],
dataLabels: {
enabled: true,
color: 'white',
format: '{point.code}'
},
name: 'Population density',
tooltip: {
pointFormat: '{point.code}: {point.value}/km²'
}
}]
};
$.getJSON('static/data/testdata1.json', function (data) {
// Make codes uppercase to match the map data
$.each(data, function () {
this.code = this.code.toUpperCase();
});
options.series.data= data;
var chart = new Highcharts.Chart(options)
});
});
You have three problems. Here's a fiddle based on their sample that uses your approach, but still uses their data, and works: http://jsfiddle.net/g29k24vw/1/
Here are the important parts:
chart : {
renderTo: 'container',
borderWidth : 1,
type: 'map'
},
And:
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=us-population-density.json&callback=?', function (data) {
// Make codes uppercase to match the map data
$.each(data, function () {
this.code = this.code.toUpperCase();
});
options.series[0].data= data;
var chart = new Highcharts.Chart(options);
});
Note the differences here:
You need to specify the chart type in options if you're going to instantiate the chart object directly instead of using the jQuery helper.
renderTo doesn't want a hash in front of the element name.
options.series[0].data, not options.series.data...series is actually an array of objects.

Data Not Showing in Highcharts

I'm attempting to combine a couple of different chart demos from Highcharts.
My examples are: Data classes and popup and Small US with data labels
I want the map from the first with the popup feature of the second. I need to connect the map to my own google spreadsheet but for now I'm just trying to get the data from the first example to work.
This is what I have so far but can't seem to get any data in the map. I thought I had a joinBy problem, and I may still, but when I set joinBy to null I thought "the map items are joined by their position in the array", yet nothing happened.
https://jsfiddle.net/9eq6mydv/
$(function () {
// Load the data from a Google Spreadsheet
// https://docs.google.com/a/highsoft.com/spreadsheet/pub?hl=en_GB&hl=en_GB&key=0AoIaUO7wH1HwdFJHaFI4eUJDYlVna3k5TlpuXzZubHc&output=html
Highcharts.data({
googleSpreadsheetKey: '0AoIaUO7wH1HwdDFXSlpjN2J4aGg5MkVHWVhsYmtyVWc',
googleSpreadsheetWorksheet: 1,
// custom handler for columns
parsed: function (columns) {
// Make the columns easier to read
var keys = columns[0],
names = columns[1],
percent = columns[10],
// Initiate the chart
options = {
chart : {
renderTo: 'container',
type: 'map',
borderWidth : 1
},
title : {
text : 'US presidential election 2008 result'
},
subtitle: {
text: 'Source: <a href="http://en.wikipedia.org/wiki/United_States_presidential_election,' +
'_2008#Election_results">Wikipedia</a>'
},
mapNavigation: {
enabled: true,
enableButtons: false
},
legend: {
align: 'right',
verticalAlign: 'top',
x: -100,
y: 70,
floating: true,
layout: 'vertical',
valueDecimals: 0,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || 'rgba(255, 255, 255, 0.85)'
},
colorAxis: {
dataClasses: [{
from: -100,
to: 0,
color: '#C40401',
name: 'McCain'
}, {
from: 0,
to: 100,
color: '#0200D0',
name: 'Obama'
}]
},
series : [{
data : data,
dataLabels: {
enabled: true,
color: '#FFFFFF',
format: '{point.code}',
style: {
textTransform: 'uppercase'
}
},
mapData: Highcharts.geojson(Highcharts.maps['countries/us/custom/us-small']),
joinBy: keys,
name: 'Democrats margin',
point: {
events: {
click: pointClick
}
},
tooltip: {
ySuffix: ' %'
},
cursor: 'pointer'
}, {
type: 'mapline',
data: Highcharts.geojson(Highcharts.maps['countries/us/custom/us-small'], 'mapline'),
color: 'silver'
}]
};
/**
* Event handler for clicking points. Use jQuery UI to pop up
* a pie chart showing the details for each state.
*/
function pointClick() {
var row = this.options.row,
$div = $('<div></div>')
.dialog({
title: this.name,
width: 400,
height: 300
});
window.chart = new Highcharts.Chart({
chart: {
renderTo: $div[0],
type: 'pie',
width: 370,
height: 240
},
title: {
text: null
},
series: [{
name: 'Votes',
data: [{
name: 'Obama',
color: '#0200D0',
y: parseInt(columns[3][row], 10)
}, {
name: 'McCain',
color: '#C40401',
y: parseInt(columns[4][row], 10)
}],
dataLabels: {
format: '<b>{point.name}</b> {point.percentage:.1f}%'
}
}]
});
}
// Read the columns into the data array
var data = [];
$.each(keys, function (i, key) {
data.push({
key: key,//.toUpperCase(),
value: parseFloat(percent[i]),
name: names,
row: i
});
});
// Initiate the chart
window.chart = new Highcharts.Map(options);
},
error: function () {
$('#container').html('<div class="loading">' +
'<i class="icon-frown icon-large"></i> ' +
'Error loading data from Google Spreadsheets' +
'</div>');
}
});
});
UPDATE:
I wanted to share with everyone my final solution. Although Ondkloss did a magnificent job answering my question the popup feature still didn't work and this is because I forgot to include the jQuery for the .dialog call. Once I included that I had an empty popup with a highchart error 17, this is because the highmaps.js code doesn't include the pie chart class. So I had to add the highcharts.js code and include map.js module afterward. You can see my final jsfiddle here.
Thanks again to Ondkloss for the excellent answer!
The problem here mostly comes down to the use of joinBy. Also to correct it there are some required changes to your data and mapData.
Currently your joinBy is an array of strings, like ["al", "ak", ...]. This is quite simply not an accepted format of the joinBy option. You can read up on the details in the API documentation, but the simplest approach is to have a attribute in common in data and mapData and then supply a string in joinBy which then joins those two arrays by that attribute. For example:
series : [{
data : data,
mapData: mapData,
joinBy: "hc-key",
]
Here the "hc-key" attribute must exist in both data and mapData.
Here's how I'd create the data variable in your code:
var data = [];
$.each(keys, function (i, key) {
if(i != 0)
data.push({
"hc-key": "us-"+key,
code: key.toUpperCase(),
value: parseFloat(percent[i]),
name: names[i],
row: i
});
});
This skips the first key, which is just "Key" (the title of the column). Here we make the "hc-key" fit the format of the "hc-key" in our map data. An example would be "us-al". The rest is just metadata that will be joined in. Note that you were referencing your data in the options prior to filling it with data, so this has to be moved prior to this.
This is how I'd create the mapData variable in your code:
var mapData = Highcharts.geojson(Highcharts.maps['countries/us/custom/us-small']);
// Process mapdata
$.each(mapData, function () {
var path = this.path,
copy = { path: path };
// This point has a square legend to the right
if (path[1] === 9727) {
// Identify the box
Highcharts.seriesTypes.map.prototype.getBox.call(0, [copy]);
// Place the center of the data label in the center of the point legend box
this.middleX = ((path[1] + path[4]) / 2 - copy._minX) / (copy._maxX - copy._minX);
this.middleY = ((path[2] + path[7]) / 2 - copy._minY) / (copy._maxY - copy._minY);
}
// Tag it for joining
this.ucName = this.name.toUpperCase();
});
The first part is your "standard map data". The rest is to correctly center the labels for the popout states, and gotten directly from the example.
And voila, see this JSFiddle demonstration to witness your map in action.
I suggest doing some console.log-ing to see how data and mapData have the hc-key in common and that leads to the joining of the data in the series.

Charts using Highcharts with multiple series from JSON

I have a JSON file of the following format :
[
{ name: 'Pay Off',
data: [ [2850,0],
[3135,0],
[3420,0],
[3705,0],
[3990,0],
[4275,0],
[4560,0],
[4845,0],
[5130,0],
[5415,0],
[5700,0],
[5985,285],
[6270,570],
[6555,855],
[6840,1140],
[7125,1425],
[7410,1710],
[7695,1995],
[7980,2280],
[8265,2565],
[8550,2850]
]
},
{
name: 'Profit',
data: [ [2850,-250],
[3135,-250],
[3420,-250],
[3705,-250],
[3990,-250],
[4275,-250],
[4560,-250],
[4845,-250],
[5130,-250],
[5415,-250],
[5700,-250],
[5985,35],
[6270,320],
[6555,605],
[6840,890],
[7125,1175],
[7410,1460],
[7695,1745],
[7980,2030],
[8265,2315],
[8550,2600]
]
}
]
I have to plot graph for 'Pay Off' and 'Profit' together. Even more plots maybe added to the list as per requirement. The data array has x-axis as 0th element and y-axis as 1st element.
What I am currently doing is the following -
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'PayOff Curve'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: []
};
$.getJSON('data.json', function(list) {
var newseries = {
name: '',
data: []
};
$.each(list, function(i,item){
newseries.name = item.name;
newseries.data = item.data;
options.series.push(newseries);
});
// Create the chart
var chart = new Highcharts.Chart(options);
});
But I don't any graph at all. I can't figure out the issue with it as I am new to both JavaScript and Python. Please suggest an efficient method to do this.
Thanks for your help..
Your JSON isn't proper one, try to validate it. Properties names shold have double quotes, change from: name: 'Pay Off' to: "name": "Pay Off"
Your JSON is valid for a highcharts series - you don't need to try to transform it at all:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'PayOff Curve'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: []
};
$.getJSON('data.json', function(list) {
options.series = list; // <- just assign the data to the series property.
var chart = new Highcharts.Chart(options);
});
});
If that still doesn't work, open the console to see whether there's a JavaScript error.
Here's a fiddle.

Categories