Using JavaScript

Before we begin, let us assure you - even though amCharts 4 was written in TypeScript, it's fully functional and ready to use in plain vanilla JavaScript apps.

We've touched briefly JavaScript topic in the Getting Started: Basics article. This one will go a bit deeper.

Installation

There are a number of options for installation. You can either download amCharts JS files for loading from your own server, or can use amCharts' CDN.

We're going to be using the latter in most of our examples and tutorials.

All of the download/install options are already listed in our previous article. In order not to bloat up this tutorial, we're not going to repeat the same information here, just a quick example of the CDN usage:

<script src="//www.amcharts.com/lib/4/core.js"></script>
<script src="//www.amcharts.com/lib/4/charts.js"></script>
<script src="//www.amcharts.com/lib/4/maps.js"></script>

Using modules

In order to optimize target app size and loading files, amCharts 4 functionality is divided into separate .js files (modules).

The one file which is always required - core.js - contains core functionality, such as SVG engine, interface elements, interactivity, etc.

IMPORTANT core.js should always come first.

The rest of the .js files are specific to group functionality. For example, charts.js brings in all of the functionality, that is required to create a charts. maps.js contains everything for creating maps.

So, to create a Pie chart, you'll need to include both core.js and charts.js. To create a map, you'll need core.js and maps.js.

Global object

All of the amCharts 4 core classes, functions and variables are available under am4core global object.

I.e. like am4core.create(), am4core.Scrollbar, etc.

Chart- and map-specific references are available in am4charts and am4maps respectively. For example, for Pie chart, its assets are accessible via am4charts object, e.g. am4charts.PieChart, am4charts.Legend, etc.

NOTE Some classes are universal and may be accessible through many namespaces. A good example is Legend, which is relevant to all chart types, and thus available in all their respective namespaces, e.g. am4charts.Legend, am4maps.Legend, etc.

Module list

Module Namespace Description
core.js am4core.* Core functionality
charts.js am4charts.* Chart functionality (XY, Pie, Sankey, Treemap, Radar, Gauge)
maps.js am4maps.* Maping functionality

Assets

Besides main functionality, you will also be using assets like themes, translations, and map geodata.

Including respective .js files will create instances in the following global variables:

Type Variable naming Example
Themes am4themes_[theme name]
<script src=".../themes/animated.js"></script>
<script>
am4core.useTheme(am4themes_animated);
</script>
Translations am4lang_[locale]
<script src=".../lang/lt_LT.js"></script>
<script>
chart.language.locale = am4lang_lt_LT;
</script>
Map data am4geodata_[map name]
<script src=".../geodata/worldLow.js"></script>
<script>
map.geodata = am4geodata_worldLow;
</script>

 

Creating a chart

In JavaScript there are two distinctive ways to create a chart:

  • Object-based approach;
  • JSON config.

The latter method, as well as cons and pros of both methods are discussed in greater detail in separate article: JSON-based config. However, we'll touch both of them here briefly. If, after going through this article, you are still not sure which one to choose, try the link above, then try creating a few charts using both methods, and see which one feels better.

Both of the methods are equally functional.

Object-based approach

Using this approach, you will be instantiating objects from various classes, including the chart itself.

PROS: Code is more readable and thus less prone to bugs and typos. Some IDEs will provide code-insight, so that might be a plus as well.

CONS: Chart config cannot be serialized. Meaning, you can't take the whole chart config and store it, say, in a database, or load dynamically via AJAX. This does not apply to data, which can still be loaded dynamically.

Instantiating chart

To instantiate a chart in JavaScript, we're going to be using a handy function am4core.create(container, chart_type_class).

The parameters are as follows.

Parameter Type Description
container HTMLElement or string A target HTML element to create the chart in.

We can pass a reference to the actual element, or we can pass an id of the element.

Below two examples will have identical results:

var chart = am4core.create(
  "chartdiv",
  am4charts.PieChart
);

var chart = am4core.create(
  document.getElementById("chartdiv"),
  am4charts.PieChart
);

NOTE The element must exist before calling create(). It won't be created if it doesn't, resulting in error.

chart_type_class Class reference or class name A reference to a chart type class, e.g. am4charts.PieChart, am4charts.XYChart, am4maps.MapChart, etc. or it's name as string (without namespace): "PieChart", "XYChart", "MapChart".

Both methods are acceptable and usable. Choose the one that suits your requirements best.

The following two code blocks are identical in functionality:

Below two examples will have identical results:

var chart = am4core.create(
  "chartdiv",
  am4charts.PieChart
);

var chart = am4core.create(
  "chartdiv",
  "PieChart"
);

TIP Technically, it is possible to use this function to instantiate non-chart elements as well, like generic container: am4core.Container. Please visit this article for further information on such usage.

Instantiating chart elements

Once we have a chart object, we can start instantiating other objects that comprise the chart, such as Legend, Series, etc.

Some singular elements, like Legend are instantiated using new notation and assigned to chart's legend property.

Others, like, say Series in a series-based chart (XY, Pie, Maps are all series-based), are created using chart's respective series property, and it's create() method.

NOTE We will not get into much detail about Series concept within this article. Please visit this separate article for more information.

// Adding a legend to a Pie chart
chart.legend = new am4charts.Legend();

// Adding a series to a Pie chart
// The following will automatically create an instance of `PieSeries`,
// attach it to `PieChart` and return the reference, so that we can
// configure it
let series = chart.series.create();

// Setting up data fields in Pie series
series.dataFields.value = "visits";
series.dataFields.category = "country";

The above series.create() method did not have any parameters, because PieChart can only have PieSeries. Some properties that are lists, like Axes, can have different items, so we need to specify their type. But we'll get to it in other articles, that specifically deal with such usage.

Configuring chart and its elements

Since we're working with objects, we configure them by setting their properties.

JSON-based approach

Using this approach, the whole chart, including all elements and settings is provided as one single JSON object.

PROS: JSON config is serializable and thus can be stored and transmitted.

CONS: More prone to typos and bugs. A single syntax typo, can bring down the whole chart, since it's one large JS structure.

Instantiating chart

Similarly to object-based approach, the chart is created using a function, albeit a different one: am4core.createFromConfig(config, container, chart_type_class).

The parameters are as follows.

Parameter Type Description
config Object A JavaScript object representing hierarchical structure of object properties and their respective values.
container HTMLElement or string A target HTML element to create the chart in.
chart_type_class Class reference or class name A reference to a chart type class, e.g. am4charts.PieChart, am4charts.XYChart, am4maps.MapChart, etc. or it's name as string (without namespace): "PieChart", "XYChart", "MapChart".

NOTE One of the difference from the cousin function create() is that both container and chart_type_class parameters are optional. If you omit them, you can add them directly into chart config, as properties "container" and "type" respectively.

NOTE am4core.createFromConfig() function will return a fully valid chart object, which you can then manipulate and change as with the object-based approach. You can update its or its children's properties, even add new elements.

Config object

NOTE Please refer to article "JSON-based config" for in-depth description on how to create complex chart configs using JSON. Or start with the brief explanation below.

Let's examine a sample Pie chart config from our introductory article:

{
	// 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": {}

}

As you can see the JSON config resembles hierarchical structure of object-based chart approach.

The top level of the config object is chart itself. Its properties are chart's properties. The above example has three of them: "series", "data", and "legend".

Since chart knows that series on a Pie chart holds a list of PieSeries, it will automatically create a PieSeries instance for each entry in our array, then set its properties, such as dataFields.

A data property expects an array of objects, so it will automatically be set to our array.

Finally, a legend can only be of one type: Legend. So the chart will automatically instantiate a Legend object and set to own legend property.

Chart data

In most cases, the data for the chart is set via its data property.

A chart's data, with some exceptions, is almost always an array of objects. E.g.:

[{
	"country": "Lithuania",
	"visites": 501
}, {
	"country": "Czech Republic",
	"visites": 301
}, {
	"country": "Ireland",
	"visites": 201
}, {
	"country": "Germany",
	"visites": 165
}, {
	"country": "Australia",
	"visites": 139
}]

Setting data

To set chart data, simply set data property of the chart.

If the chart already had data set, it will take in the new data and redraw itself. No actions further necessary.

Setting data fields

Depending on chart type, you will also need to configure chart's respective Series so that they know which fields in data contain the information they need.

That's where dataFields property comes into play.

As we saw earlier in part on Instantiating chart elements, a PieSeries needs two data fields to make a sense of the data:

  1. One that holds numeric value; (value)
  2. One that holds title for the slice. (category)

Different chart types will have more complex dataField configurations. Please refer to an articles on specific chart types, for more in-depth information about those. We are not going to get into particular details here.

External data

The charts in V4 have built-in capabilities to dynamically load external data in CSV and JSON formats.

To make the chart load external data, we need to use chart's dataSource property, instead of data.

There's a separate article on external data here, so we'll just touch the topic briefly here.

A dataSource is an object of type DataSource which specifies the URL, the type, and possibly some related settings.

As an example, here's how we would rework previous Pie chart examples, to load the data from an external URL:

chart.dataSource.url = "pie.json";
{
  // ...
  "dataSource": {
    "url": "pie.json"
  }
}

If we wanted to load data in, say, CSV, we'd also need to set data parser, and, most probably, instructions about the format. (separator, etc.)