How to Embed amCharts Into a Web Page

In this blog post, we show several methods for embedding an amCharts chart into a web page.

Here's the simple amCharts pie chart we will be creating:

The amCharts pie chart has some basic interactivity when you click on a pie slice or on any item in the legend. This is a very simple example of an amCharts chart as the point is to show methods of embedding rather than chart functionality and interactivity.

3 methods to embed amCharts into a webpage

  1. Single HTML file with internal CSS and internal JavaScript
  2. Separate static files (HTML, CSS, and JavaScript) with amCharts JSON config and data embedded in the JavaScript
  3. Loading external files (amCharts JSON config and data) - This is our recommended approach

All of these methods result in the exact same simple chart above.

For all three of these methods, we are using amCharts 4 and the amCharts JSON-based config rather than the object based approach.

What is the amCharts JSON-based config?

amCharts 4 offers two ways to configure and create charts: the object-based approach and the JSON-based config. For this article, we’ll focus on the latter. JSON config lets users create charts from a single JS object that contains all of the data needed for the chart.

The pros of using JSON config are:

  • It’s serializable, meaning that you can save, load, and transfer the entire chart without losing anything. You can’t do this with regular objects -- if you try to save a regular chart object to a database, it’s not going to work.
  • Being serializable opens up a ton of charting possibilities -- you can have a dynamic dashboard that loads a chart config and data to display for the user based on their interaction without them ever needing to refresh the page.
  • For many users, JSON feels more readable and natural -- most likely because of its prominent hierarchical structure than is less obvious with objects.

The cons of using JSON config are:

  • JSON is much more sensitive to errors. A single character missed anywhere can invalidate the entire config, preventing the chart from displaying at all.

How JSON Works

Chart, and all of its descent elements, are JS objects. These objects can have properties and methods. Methods cannot be represented by JSON, so we’ll focus on properties. Every object has a list of properties. They can be of basic types, like strings or numbers, arrays of elements, or various other objects. Those property objects can have their own properties; this is why JSON uses a hierarchical structure. Now, let’s look at some examples of amCharts.

Prerequisites

Web Server

We will be using a Python HTTP server to in these examples.

Check to see if Python 3 is already installed by typing python or python3 on your command line. If it is not installed, you can download Python 3 here and follow install instructions here.

Beginner Python: Drawing Symbols
In this tutorial, use Python to draw a symbol any Harry Potter fan will recognize. Python is a general-purpose, object-oriented programming language that is used across all realms of development including web applications,

Get started: Run the Python HTTP server

Create an empty directory on your machine. This is the directory where we will be creating our files and running the Python HTTP server.

# change the current working directory to your home directory
cd
# create an empty folder named amcharts
mkdir amcharts
# change directory into the newly created folder
cd amcharts

Spinning up a Python 3 HTTP server is very simple. You can read more about this here.

python3 -m http.server

You should see this on the command line:

Open a web browser and go to http://localhost:8000/.

You should see this:

Method 1: Single HTML file with internal CSS and internal JavaScript

This is the simplest and least scalable method.

See Method 2 for an explanation of the code.

index.html

<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>amCharts</title>
    <script src="//www.amcharts.com/lib/4/core.js"></script>
    <script src="//www.amcharts.com/lib/4/charts.js"></script>
    <style>
        #chart {
            width: 100%;
            height: 400px;
        }   
    </style>
</head>
<body>
    <h1>amCharts - Single HTML file</h1>
    <div id="chart"></div>
    <script type="text/javascript">
        var chart = am4core.createFromConfig({
            // Create pie series
            "series": [{
                "type": "PieSeries",
                "dataFields": {
                    "value": "litres",
                    "category": "country"
                }
            }],
            // Add data
            "data": [
                {
                    "country": "Lithuania",
                    "litres": 501.9
                },
                {
                    "country": "Czech Republic",
                    "litres": 301.9
                },
                {
                    "country": "Ireland",
                    "litres": 201.1
                },
                {
                    "country": "Germany",
                    "litres": 165.8
                },
                {
                    "country": "Australia",
                    "litres": 139.9
                },
                    {
                    "country": "Austria",
                    "litres": 128.3
                },
                {
                    "country": "UK",
                    "litres": 99
                },
                {
                    "country": "Belgium",
                    "litres": 60
                },
                {
                    "country": "The Netherlands",
                    "litres": 50
                }
            ],
            // And, for a good measure, let's add a legend
            "legend": {}

        }, "chart", "PieChart");
    </script>
</body>
</html>

Method 2: Separate static files (HTML, CSS, and JavaScript) with amCharts JSON config and data embedded in the JavaScript

In this method we break out the HTML, CSS, and JavaScript into their own separate files. There is no difference in the overall code, but the code is easier to understand and maintain going forward.

index.html

<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>amCharts</title>
    <script src="//www.amcharts.com/lib/4/core.js"></script>
    <script src="//www.amcharts.com/lib/4/charts.js"></script>
    <link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
    <h1>amCharts - Separate Files</h1>
    <div id="chart"></div>
    <script src="js/script.js"></script>
</body>
</html>

Key components in the index.html:

  • We load amCharts scripts (core.js and charts.js) from the amCharts CDN.
  • We create an empty div with id chart that will be used by the JavaScript to render the amCharts chart.
  • The js/script.js is loaded after the div.

css/style.css

#chart {
  width: 100%;
  height: 400px;
}

Basic CSS styling of the chart div.

js/script.js

var chart = am4core.createFromConfig({
    // Create pie series
    "series": [{
        "type": "PieSeries",
        "dataFields": {
            "value": "litres",
            "category": "country"
        }
    }],
    // Add data
    "data": [
        {
            "country": "Lithuania",
            "litres": 501.9
        },
        {
            "country": "Czech Republic",
            "litres": 301.9
        },
        {
            "country": "Ireland",
            "litres": 201.1
        },
        {
            "country": "Germany",
            "litres": 165.8
        },
        {
            "country": "Australia",
            "litres": 139.9
        },
            {
            "country": "Austria",
            "litres": 128.3
        },
        {
            "country": "UK",
            "litres": 99
        },
        {
            "country": "Belgium",
            "litres": 60
        },
        {
            "country": "The Netherlands",
            "litres": 50
        }
    ],
    // And, for a good measure, let's add a legend
    "legend": {}
    
}, "chart", "PieChart");

Key components in the js/script.js:

  • The amCharts chart is created using the amCharts JSON-based config. This is in line 1: am4core.createFromConfig({...}). We separate the amCharts JSON config into its own file in Method 3.
  • Data for the chart ("data": [...]) is embedded in the JavaScript code. We separate this data into its own file in Method 3. For more information on the data structure required by amCharts, see this.

Method 3: Loading external files (amCharts JSON config and data)

This method is our recommended approach as it completely separates the amCharts JSON config and data from the front end code.

index.html

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>amCharts</title>
  <script src="//www.amcharts.com/lib/4/core.js"></script>
  <script src="//www.amcharts.com/lib/4/charts.js"></script>
  <link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
    <h1>amCharts - Loading external files (amCharts config and data)</h1>
    <div id="chart"></div>
    <script src="js/script.js"></script>
</body>
</html>

Nothing new here.

css/style.css

#chart {
  width: 100%;
  height: 400px;
}

Nothing new here.

js/script.js

// load the amCharts chart's config from a JSON file
var amChartsConfig = new am4core.DataSource();
amChartsConfig.url = "json/config.json";
amChartsConfig.load();

// create the amChart chart using the JSON config
var chart
amChartsConfig.events.on("done", function(ev) {
  chart = am4core.createFromConfig(
    config = amChartsConfig.data,
    container = "chart",
    chart_type_class = "PieChart"
  );
});

The JavaScript in this method has changed significantly.

Key components in the js/script.js:

  • Lines 2-4: The amCharts JSON config is loaded from an external file (json/config.json) rather than being hard coded into the JavaScript. This separates the configuration of the amChart from the actual front end code of the page. For more information on using amCharts to load external files, see the Standalone usage section of amCharts's Loading External Data documentation.
  • Lines 7-14: The amCharts chart is created from the loaded amCharts JSON config above. The chart is created AFTER the JSON config is fully loaded (amChartsConfig.events.on("done", ...)).

json/config.json

{
  "series": [{
    "type": "PieSeries",
    "dataFields": {
      "value": "litres",
      "category": "country"
    }
  }],
  "dataSource" : {
    "url": "json/data.json"
  },
  "legend": {}
}

This is the amCharts JSON config file referenced by the js/script.js above.

Key components in the json/config.json:

  • The data used to build the chart is separated from the config of the chart itself. dataSource references another file (json/data.json). This simplifies the configuration of the chart. If the data in json/data.json changes, the chart will reflect those changes without any manual intervention. For more information, see amCharts's documentation on "Loading External Data".

json/data.json

[
  {
    "country": "Lithuania",
    "litres": 501.9
  },
  {
    "country": "Czech Republic",
    "litres": 301.9
  },
  {
    "country": "Ireland",
    "litres": 201.1
  },
  {
    "country": "Germany",
    "litres": 165.8
  },
  {
    "country": "Australia",
    "litres": 139.9
  },
  {
    "country": "Austria",
    "litres": 128.3
  },
  {
    "country": "UK",
    "litres": 99
  },
  {
    "country": "Belgium",
    "litres": 60
  },
  {
    "country": "The Netherlands",
    "litres": 50
  }
]

This is the data referenced by the amCharts config file above (json/config.json).

Key components in the json/data.json:

  • The data is completely separated from the front end code (HTML, CSS, and JavaScript) and from the amCharts chart's config (json/config.json).

Conclusion

We covered three methods to embed amCharts into a webpage:

  1. Single HTML file with internal CSS and internal JavaScript
  2. Separate static files (HTML, CSS, and JavaScript) with amCharts JSON config and data embedded in the JavaScript
  3. Loading external files (amCharts JSON config and data)

The recommended method (#3) completely separates the front end code (HTML, CSS, and JavaScript) from the amCharts JSON config and data.

See how we serve up data with our embedded analytics product, Zuar Portals.

Zuar Portal | Expand the capabilities of your Analytics
Learn why you need a visual analytics portal, how you can brand your own with Zuar, and our scalable portal pricing plans. Start your 2 week trial today.
What is Embedded Analytics? | Zuar
It’s a common misconception that Embedded Analytics is just for large enterprises. Learn how you can use it to your advantage.