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: , ,
25 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

  7. roberto says:

    How load data from data base when in getjson use a select, i have in html

    – Select Vendor –
    Corning
    Solid 2000

    on js
    function populateFruitVariety() {
    $.getJSON(‘data.php’, {vendors:$(‘#vendors’).val()}, function(data) {

    var jsonString = JSON.stringify(data) ;//asuming result is a JSON object.
    console.log(data[1]);
    });

    }

    $(document).ready(function() {

    populateFruitVariety();
    $(‘#vendors’).change(function() {
    populateFruitVariety();

    });

    });
    on php
    query($sql);
    while ($r = $result->fetch_assoc()) {
    $row1[‘name’] = $r[‘NM_DAS’];
    $row1[‘data’][] = $r[‘ALARMS’];
    $row3[‘category’][] = $r[‘Fecha’];
    }
    $rslt = array();
    array_push($rslt, $row1);
    array_push($rslt, $row3);
    print json_encode($rslt, JSON_NUMERIC_CHECK);

    $con->close();
    }
    exit();
    ?>
    the getjson result is empty i try this for validate in php file

    if( isset($_GET[‘vendors’]) ) {
    $vendor =$_GET[‘vendors’];
    print json_encode($vendor, JSON_NUMERIC_CHECK);

    and i get a value of option
    but something more complex i can’t do it

  8. Tushar Upadhyay says:

    Hey Debasis !
    I went through your illsutrations and they were really helpful for me to understand the concept of loading a file, I am stuck with a problem.
    I am making a live spline chart updating every second using highcharts and want to upload the data of the json file to it.The json file is stored in the same directory as that of the html page.
    Can I you help me if i send you the code snippet ?

  9. Shiv says:

    Thank you for this helpful post

  10. Shilpa says:

    Hi ,Debasis Das
    AS Javier, said me too getting a blank page, will place my code here am trying to return data from a controller not sure weather I can do so or not please guide me view code is exactly as your working copy.

    Controller code:
    public string Returndata()
    {dynamic gObject = new graphdata();
    gObject.key = “Website_visits”;
    gObject.value = 15654;
    var json = new JavaScriptSerializer().Serialize(gObject);
    return (json);
    }
    view:
    $(function () {
    var processed_json = new Array();
    $.getJSON(‘/Graph/Returndata’, function (data) {
    // Populate series
    for (i = 0; i < data.length; i++) {
    processed_json.push([data[i].key, data[i].value]);
    }
    Data:
    The data returned is {"Key":"Website_visits","value":15654}
    their is not plot on the graph just a empty lay out

    • Shilpa says:

      Hi Debasis Das,
      I got it the modification I made was converted the json objects into java script array by using

      for (i = 0; i < data.length; i++) {
      processed_json.push([data[i].year, parseInt(data[i].populations)]);
      }
      then It worked
      the complete UI code
      $(document).ready(function () {
      $.ajax({
      type: "GET",
      url: '/Graph/Returndata',
      dataType: "json",
      contentType: "application/json",
      crossDomain: true,
      success: function (data) {
      console.log(data);
      // Populate series
      var processed_json = new Array();

      for (i = 0; i < data.length; i++) {
      processed_json.push([data[i].year, parseInt(data[i].populations)]);
      }

      // draw chart
      $('#container').highcharts({
      chart: {
      type: "column"
      // type: "funnel"
      },
      title: {
      text: "City Population"
      },
      xAxis: {
      allowDecimals: false,
      title: {
      text: "Year"
      }
      },
      yAxis: {
      title: {
      text: "Population"
      }

      },
      series: [{
      data: processed_json
      }]
      });

      }

      });

      });
      Thank You
      Can you guide how to stream live data

      • Shilpa says:

        Actually I was trying to pass a single object from the controller so it was not able to convert it into array of js so returned a list from controller then it was able to convert it into java script array
        Controller code is as follows

        public ActionResult Returndata()
        {

        dynamic gObject = new graphdata();
        gObject.year = “1992”;
        gObject.populations = 15654;

        List obj2 = new List();
        obj2.Add(gObject);
        obj2.Add(new graphdata { year = “1993”, populations = 16654 });
        obj2.Add(new graphdata { year = “1994”, populations = 17654 });
        return Json(obj2, JsonRequestBehavior.AllowGet);

        }

  11. Sudhanva says:

    Hi,
    I went through your code which used json data to render a column chart. Can you please help me to do the same with pie chart.

  12. Muhammad Siddique says:

    Hi Thanks for your article 🙂 and i need little more help i have to know is there any way to use no-data-to-display.js file in our multi level pie chart ?
    Consider District, City and Union Council UC,
    ‘District – Grand Parent’
    ‘City – parent’
    ‘UC – child’
    now in as a franchiser we have to see where and where we are selling our products.
    my problem is when there is only distribution in district it drillDown and shows message “we are only selling in …… district”

    else it shows different cities and then uc wherever we are ending it shows message.

    it is working but it is not showing message until it is not completely empty
    how do i do that please answer thanks.

  13. sreenivasulu says:

    React Local

    <!—->
    <!—->

    <!—->

    csv file:

    Sales by source January February March April May June July
    Search engine 60 64 57 61 54 58 61
    Ad 30 39 32 40 37 33 41
    Affiliate 20 18 23 27 19 23 27
    Newsletter 29 22 23 27 19 32 34
    Offline/Organic 50 47 44 40 48 51 53

    jsxfile:

    class Test2 extends React.Component {

    generateChart()
    {
    var options = {
    chart: {
    renderTo: ‘container’,
    type: ‘scatter’

    },
    title: {
    text: ‘Tiny Tool Monthly Sales’
    },
    subtitle: {
    text: ‘2014 Q1-Q2’
    },
    xAxis: {
    categories: []
    },
    yAxis: {
    title: {
    text: ‘Sales’
    }
    },
    series: []
    };

    $.get(‘test1.csv’, function(data) {
    var lines = data.split(‘\n’);
    $.each(lines, function(lineNo, line) {
    var items = line.split(‘,’);

    if (lineNo == 0) {
    $.each(items, function(itemNo, item) {
    //skip first item of first line

    if (itemNo > 0) options.xAxis.categories.push(item);
    document.writeln(item);
    });
    }

    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);

    }

    })
    //putting all together and create the chart
    var chart = new Highcharts.Chart(options);
    });
    }

    render() {
    return (

    CLICK

    );
    }

    }

    // ========================================

    /*
    ReactDOM.render(
    ,
    document.getElementById(‘root’)
    );
    */

    ReactDOM.render(
    ,
    document.getElementById(‘root’)
    );

    Hi please help me to create react app.

  14. 토토천국 says:

    Thanks for finally writing about >Different Ways of Loading highcharts data – Knowledge Stack <Liked it!

  15. Mangesh says:

    I’m using highcharts for android device,
    my problem is it takes time load charts initially how to handle this,
    also how can I adjust charts size for different size devices.

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 *

*