Different Ways of Loading highcharts data

Different Ways of Loading highcharts data

Created By: Debasis Das (8-Jan-2015)

In this article we will demonstrate different ways of loading a highcharts by feeding data from different sources types.

We will demonstrate the following data load types

  • Loading highcharts from data defined in the highcharts data series
  • Loading highcharts data from csv by manually parsing the csv
  • Loading highcharts data from csv by using the highcharts data module.
  • Loading highcharts data from a JSON file/ JSON Response
  • Loading highcharts data from a csv defined as innerHTML of a hidden div

Highcharts- Demo 1 (Data defined in HTML – Highcharts Data Series

Highcharts-Demo1

 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Highcharts- Demo 1 (Data defined in HTML - Highcharts Data Series</title>
    <style>
		body{
			margin-top: 30px;
			margin-left:40px;
		}
				pre	{
		border:1px solid red;
		}

    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
	<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>

<body>
   <div style="width: 800px; margin: 2em auto; padding: 1em; border: 1px solid red; border-radius: 0.5em">
	Highcharts data defined in series. This is the default expected behavior.
	</div>
<div id="container" style="width:1024px; min-width: 310px; height: 400px; margin: 0 auto"></div>
<script type="text/javascript">
$(function () {
        $('#container').highcharts({
            chart: {
                type: 'column'
            },
            title: {
                text: 'Monthly Average Rainfall'
            },
            subtitle: {
                text: 'Source: WorldClimate.com'
            },
            xAxis: {
                categories: [
                    'Jan',
                    'Feb',
                    'Mar',
                    'Apr',
                    'May',
                    'Jun',
                    'Jul',
                    'Aug',
                    'Sep',
                    'Oct',
                    'Nov',
                    'Dec'
                ]
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Rainfall (mm)'
                }
            },
            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:.1f} mm</b></td></tr>',
                footerFormat: '</table>',
                shared: true,
                useHTML: true
            },
            plotOptions: {
                column: {
                    pointPadding: 0.2,
                    borderWidth: 0
                }
            },
            series: [{
                name: 'Tokyo',
                data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    
            }, {
                name: 'New York',
                data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3]
    
            }, {
                name: 'London',
                data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2]
    
            }, {
                name: 'Berlin',
                data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1]
            }]
        });
});
</script>
</body>
</html>

Highcharts Demo 2- Data from CSV, Manual Parsing of CSV

Highcharts-Demo2

	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Highcharts Data from CSV manual parsing</title>
		<style>
		body{
			margin-top: 30px;
			margin-left:40px;
		}
				pre	{
		border:1px solid red;
		}

		</style>
		<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">
		$(document).ready(function() {
			var options = {
				chart: {
					renderTo: 'container',
					type: 'column'
				},
				title: {
					text: 'Fruit Consumption'
				},
				xAxis: {
					categories: []
				},
				yAxis: {
					title: {
						text: 'Units'
					}
				},
				series: []
			};
			
			/*
			 Load the data from the CSV file. This is the contents of the file:
				Apples,Pears,Oranges,Bananas,Plums
				John,8,4,6,5
				Jane,3,4,2,3
				Joe,86,76,79,77
				Janet,3,16,13,15
			 */ 
			$.get('data.csv', function(data) {
				// Split the lines
				var lines = data.split('\n');
				$.each(lines, function(lineNo, line) {
					var items = line.split(',');
					
					// header line containes categories
					if (lineNo == 0) {
						$.each(items, function(itemNo, item) {
							if (itemNo > 0) options.xAxis.categories.push(item);
						});
					}
					// the rest of the lines contain data with their name in the first position
					else {
						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);
			});
		});
	</script>
</head>
<body>
	<div style="width: 800px; margin: 2em auto; padding: 1em; border: 1px solid red; border-radius: 0.5em">
	NOTE: This demo shows a way of manually parsing CSV. As of Highcharts 4.0 this is
	not necessary for simple CSV files, as this functionality is built into the 
	<a href="http://api.highcharts.com/#data">Data module</a>.
	</div>
	<!-- 3. Add the container -->
	<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>

Highcharts- Data from csv in innerHTML of hidden div using highcharts data module

Highcharts-Demo3

	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Highcharts Data from innerHTML of hidden div</title>
		<style>
		body{
			margin-top: 30px;
			margin-left:40px;
		}
				pre	{
		border:1px solid red;
		}

		</style>
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>		
		<script src="http://code.highcharts.com/highcharts.js"></script>
		<script src="http://code.highcharts.com/modules/data.js"></script>
		<script src="http://code.highcharts.com/modules/exporting.js"></script>
	</head>
<body>
	<div style="width: 800px; margin: 2em auto; padding: 1em; border: 1px solid red; border-radius: 0.5em">
	Highcharts data load from a csv stored inline in a hidden div
	</div>

	<div id="container" style="width:1024px; min-width: 310px; height: 400px; margin: 0 auto"></div>
<pre id="csv" style="display:none">Apples,Pears,Oranges,Bananas,Plums
John,8,4,6,5
Jane,3,4,2,3
Joe,16,26,29,17
Janet,3,16,13,15
</pre>
<script type="text/javascript">
	$(function () {
		$('#container').highcharts({
				chart: {
					type: 'column'
				},

			title: {
				text: 'Fruit Consumtion'
			},

			subtitle: {
				text: 'Data input from CSV'
			},

			data: {
				csv: document.getElementById('csv').innerHTML
			},

			plotOptions: {
				series: {
					marker: {
						enabled: false
					}
				}
			},
			series:[]
		});
	});
</script>
</body>
</html>

Highcharts data from JSON Response

Highcharts-Demo4

    <!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Highcharts data from JSON Response</title>
		<style>
		body{
			margin-top: 30px;
			margin-left:40px;
		}
		</style>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>		
	<script src="http://code.highcharts.com/highcharts.js"></script>
	<script type="text/javascript">
        $(function () {
                var processed_json = new Array();   
                $.getJSON('http://localhost:8080/charts_demo/data.json', function(data) {
                    // Populate series
                    for (i = 0; i < data.length; i++){
                        processed_json.push([data[i].key, data[i].value]);
                    }
                 
                    // draw chart
                    $('#container').highcharts({
                    chart: {
                        type: "column"
                    },
                    title: {
                        text: "Student data"
                    },
                    xAxis: {
                        type: 'category',
                        allowDecimals: false,
                        title: {
                            text: ""
                        }
                    },
                    yAxis: {
                        title: {
                            text: "Scores"
                        }
                    },
                    series: [{
	                    name: 'Subjects',
                        data: processed_json
                    }]
                }); 
            });
        });
    </script>
</head>
<body>
   <div style="width: 800px; margin: 2em auto; padding: 1em; border: 1px solid red; border-radius: 0.5em">
	Highcharts data load from a JSON using manual JSON Processing
	</div>
    <div id="container" style="height: 400px"></div>
    
</body>
</html>

Highcharts Data loaded from a csv file using highcharts data module

Highcharts-Demo5

<!DOCTYPE html>
 
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Highcharts Data loaded from a csv file using highcharts data module</title>
		<style>
		body{
			margin-top: 30px;
			margin-left:40px;
		}
		</style>
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>		
		<script src="http://code.highcharts.com/highcharts.js"></script>
				<script src="http://code.highcharts.com/modules/data.js"></script>
</head>
<body>
	<div style="width: 800px; margin: 2em auto; padding: 1em; border: 1px solid red; border-radius: 0.5em">
	NOTE: This demo shows a way loading the highcharts data from a csv file using the highcharts data module.
	<a href="http://api.highcharts.com/#data">Data module</a>.
	</div>
    <div id="container" style="height: 400px"></div>
        <script type="text/javascript">
$(function () {
$.get('data.csv', function(data) {
 $('#container').highcharts({
			chart: {
				type: "column"
			},
			title: {
				text: "Fruit Consumtion"
			},
			xAxis: {
				categories: []
			},
			yAxis: {
				title: {
					text: "Number of students"
				}
			},
			data: {
				csv: data
				//csv: document.getElementById('csv').innerHTML
			},
			plotOptions: {
				series: {
					marker: {
						enabled: false
					}
				}
			}
	});
});
});
    </script>
</body>
</html>
Posted in Charts n Graphs, CSS, HTML5 Tagged with: , ,
12 comments on “Different Ways of Loading highcharts data
  1. Lepsik says:

    Thank you for examples.
    Could you add several additions to example: Highcharts data from JSON Response
    1. What inside of this file? http://localhost:8080/charts_demo/data.json

    2. I have http://www.site.com/page.aspx providing json data – is it possible to use?

    Thanks a lot.

  2. binoy says:

    hi, i have a question on fetching values from json.. U have fecthed values from json using the for loop (processed_json.push([data[i].key, data[i].value]);).. What if there are more than two values?? say 4 or 5 values.. how to add them and display it??

  3. Mahamud says:

    Thank you so much for this. :)

  4. Chen Wei says:

    Hi Debasis,

    Thanks for your sharing. :)

    I have a question: I am using your code (from JSON response one) to push data. But my data key is date, in the format of {“key”:”Date.UTC(2016, 0, 20)”,”value”:8}, etc. If I define my data series in HTML, it works fine.

    But if I push from json file, it does not work properly. It shows 1.Jan ; 00:00:00.001; 00:00:00.002, etc. on the x-axis.

    Do you have any solutions?

    Thank you!

  5. Nice article, various chart explained.

  6. Al says:

    Hi,
    thanks for the nice article but I have an open point. How do I load 2 or more JSON files into the same chart?
    FYI, I’m not the Java expert and intuitively I have thought I could run the read-data function into two different variables and load the series to one chart. In my case I just see an empty chart.

    The code I tried looks like

    Highcharts data from JSON Response

    body{
    margin-top: 30px;
    margin-left:40px;
    }

    $(function () {
    var ytkm2015 = new Array();
    $.getJSON(‘https://mysite/www/inc/data/2015-yearly-distance-kv.json’, function(data) {
    // Populate series
    for (i = 0; i < data.length; i++){
    ytkm2015.push([data[i].key, data[i].value]);
    }
    });
    var ytkm2016 = new Array();
    $.getJSON('https://mysite/www/inc/data/2016-yearly-distance-kv.json&#039;, function(data) {
    // Populate series
    for (i = 0; i < data.length; i++){
    ytkm2016.push([data[i].key, data[i].value]);
    }
    });
    // draw chart
    $('#container').highcharts({
    chart: { type: "line" },
    title: { text: "Yearly Distance" },
    xAxis: { type: 'category', allowDecimals: false, title: { text: "" }, ceiling: 366, min: 1, max: 266 },
    yAxis: { title: { text: "Kilometers" } },
    series: [
    { name: '2015', color: '#AABBCC', data: ytkm2015 },
    { name: '2016', color: '#BB0000', data: ytkm2016 }
    ]
    });
    });

    Highcharts data load from a JSON using manual JSON Processing

    The JSON files looks like below and they are OK as I can create the chart if I load them separate.
    2015:
    [{“key”:”11″,”value”:31.9},{“key”:”11″,”value”:31.9},{“key”:”14″,”value”:63.8},{“key”:”16″,”value”:94.34},{“key”:”17″,”value”:146.94},{“key”:”31″,”value”:146.94},{“key”:”32″,”value”:146.94},{“key”:”37″,”value”:179.95}]

    2016:
    [{“key”:”8″,”value”:2.44},{“key”:”8″,”value”:2.44},{“key”:”9″,”value”:47.74},{“key”:”11″,”value”:52.8},{“key”:”11″,”value”:60.68},{“key”:”34″,”value”:101.81},{“key”:”36″,”value”:126.97}]

    Thanks for any suggestion,
    Al

1 Pings/Trackbacks for "Different Ways of Loading highcharts data"
  1. URL says:

    … [Trackback]

    […] Read More here: knowstack.com/different-ways-of-loading-highcharts-data/ […]

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts


Hit Counter provided by technology news