Advertisement
  1. Code
  2. JavaScript

Create Interactive Charts Using Plotly.js, Part 1: Getting Started

Scroll to top
This post is part of a series called Create Interactive Charts Using Plotly.js.
Create Interactive Charts Using Plotly.js, Part 2: Line Charts

In the series titled Getting Started With Chart.js, you learned how to use Chart.js to easily create responsive canvas-based charts. The series covered seven basic chart types offered by the library. However, you may be required to create more complex charts with additional functionality to make those charts interactive.

One of the best free-to-use libraries to create a variety of responsive, interactive, and functionality-rich charts is Plotly.js. In this series, you will learn how to create different kinds of charts using Plotly.js, including line charts, bar charts, bubble charts, and dot plot charts.

Why Use Plotly.js?

Plotly.js offers a lot of features that make learning about the library worth the effort. It is a high-level declarative library built on top of d3.js and stack.gl. Here is a list of features that make Plotly one of the best JavaScript charting libraries:

  • You can create interactive charts with ease using Plotly.js. Any chart that you create with the library is equipped with features like zooming in, zooming out, panning, auto-scaling, etc. These features are very useful when you want to study charts with a large number of plotted points. All these events are exposed in the API, so you can write custom code to perform your own actions when any of these events are triggered.
  • High performance when plotting a lot of points makes Plotly.js a great choice whenever you have to chart a large amount of data. Since most charts are created using SVG, you get a decent amount of compatibility across browsers and the ability to export high-quality images of any chart. However, drawing a large number of SVG elements in the DOM can adversely affect the performance. The library uses stack.gl to create high-performance 2D and 3D charts.
  • Any 3D charts that you create are rendered with the help of WebGL to take full advantage of all the power that the GPU has to offer.
  • All the Plotly.js charts are fully customizable. Everything from the colors and labels to grid lines and legends can be customized using a set of JSON attributes. You will learn how to customize different chart types in the next three parts of the series.

Installing Plotly

Before we start using Plotly.js, we need to install it first. There are a lot of different ways to install the library.

The first option is to perform the installation using npm by running the following command:

1
npm install plotly.js

This option is probably the most elegant and flexible. However, you will need to set up a bundler, which automatically transforms npm packages you use into something the browser can process. Additionally, in order to actually use the package, you probably want to use ESM. You can read more about ESM here.

If you want a quick solution for prototyping, you can also use the Plotly.js CDN and directly link to the library:

1
<script type="text/javascript" src="https://cdn.plot.ly/plotly-2.14.0.min.js"></script>

At the time of writing this tutorial, the latest version of the library is 2.14.0. The file size after minifying and compressing the library is 1.1 MB. The non-minified and uncompressed version has a size of 3.5 MB. As you can see, the long list of features that this library offers come at a price.

Starting from version 1.15, you can choose from different partial bundles, each of which allows you to create specific chart types. There are seven different bundles: basic, cartesian, geo, gl3d, gl2d, mapbox, finance, and strict. You can get the CDN link for these bundles using the following line:

1
https://cdn.plot.ly/plotly-bundleName-2.14.0.min.js
2
3
// Therefore the basic bundle becomes:
4
https://cdn.plot.ly/plotly-basic-2.14.0.min.js
5
6
// and the cartesian bundle becomes:
7
https://cdn.plot.ly/plotly-cartesian-2.14.0.min.js

Alternatively, if you are using NPM, you can install a package for that bundle.

1
npm install plotly.js-bundleName-dist

If you only need to draw charts from a single bundle, you can use this method to significantly reduce the file size. Here is some additional information about each of them.

  • basic: This bundle contains the scatter, bar, and pie trace modules. The compressed and minified version of this bundle has a size of 215.7 kB.
  • cartesian: This bundle contains the scatter, bar, box, heatmap, histogram, histogram2d, histogram2dcontour, pie, contour, and scatterternary trace modules. The compressed and minified version of this bundle has a size of 238.2 kB.
  • geo: This bundle allows you to create different types of map-related charts in JavaScript. The compressed and minified version of this bundle has a size of 224.1 kB.
  • gl3d: This bundle allows you to create different types of 3D maps using the scatter, scatter3d, surface, and mesh3d trace modules. The compressed and minified version of this bundle has a size of 354 kB.
  • gl2d: This bundle contains the scatter, scattergl, pointcloud, heatmapgl, contourgl, and parcoords trace modules. It has a size of 362.9 kB after minification and compression.
  • mapbox: This bundle contains the scatter and scattermapbox trace modules. The file size in this case is 328.6 kB.
  • finance: The finance bundle can be used to create time series, candlestick and other chart types to plot financial data. This module consists of scatter, bar, histogram, pie, ohlc, and candlestick trace modules.
  • strict: The strict bundle includes everything the normal bundle has, but avoids function constructors. This bundle is 10% larger than the standard bundle, so do not use it unless you really need it.

Using Plotly to Create a Chart

Once you have decided on the charts that you want to create and loaded the appropriate bundle in your webpage, you can start creating your own charts using Plotly.js. The first thing that you need to do is create an empty div element where the graph should be drawn.

Have some data ready that you want to plot on the chart. In this example, I am just using some random numbers to create the chart. Finally, you have to call the plot() function and provide it with all the information like the container div, the data, and the layout options. Here is the code to create a very basic line chart:

1
// if you are using npm and esm add

2
// import Plotly from "plotly.js"

3
const lineDiv = document.getElementById('line-chart');
4
5
const traceA = {
6
  x: [1, 2, 3, 4, 16, 17, 26],
7
  y: [1, 40, 9, 60, 4, 20, 10],
8
  type: 'scatter'
9
};
10
11
const data = [traceA];
12
13
const layout = {
14
  title: 'A Line Chart in Plotly'
15
};
16
17
Plotly.newPlot( lineDiv, data, layout );

All charts in Plotly.js are created declaratively using JSON objects. Every property of the chart, like its color and data, has a corresponding JSON attribute that can be used to fully customize the appearance and behavior of the chart.

The attributes can be broadly divided into two categories. The first one is called traces, which are objects that are used to provide information about a single series of the data to be plotted on the graph. The second category is layout, which provides different attributes that control all the other aspects of the chart like its title or annotations. Different traces are further categorized by the chart type, and the attributes that are available to you to draw the chart will depend on the value of the type attribute.

In the above example, we have created a traceA object that stores the trace type and the data that you want to plot on the chart. The following CodePen demo shows the final result of the above code.

As you can see in the demo, you can zoom in, zoom out, or auto-scale the graph. You can also download the chart as an image. The chart itself looks very professional with its sharp lines.

Layout Attributes to Customize the Charts

In the rest of the tutorials in this series, we will focus on learning about different attributes related to specific chart types like line and bar charts. Before doing that, you should also have some basic knowledge of different layout attributes that control aspects common to all chart types like the font, the title, the x-axis, the y-axis, etc.

You can specify a global font which should be used while creating traces and other layout components like the axes and the title. The options are specified using the font object, and these values are used by default by all the components of the chart. The color, size, and family keys are nested inside the font key. You can use them to set the global font color, global font size, and global font-family respectively.

Each chart has a title attribute which can be used to set the title for the current chart. It gives the user some information about what you are plotting on the chart. The font properties for the title can be specified using the titlefont attribute. Just like the global font attribute, the color, size and family keys nested inside the titlefont attribute can be used to control the font-related properties of the title.

You can specify the width and height of a chart in pixels using the width and height keys. You can also control the spacing around the chart as well as the plotting area using different attributes nested under the margin key. All the values are specified in pixels.

The left margin is specified using the l attribute, the right margin using the r attribute, the top margin using the t attribute, and the bottom margin using the b attribute. The plotting area and the axis lines are very close to each other by default. You can add some space around the plotting area using the pad attribute nested inside the margin key. The padding is specified in pixels, and its default value is zero.

You can choose your own colors for the background of the whole chart as well as the plotting area to match the theme of your website. Both these colors are set to white by default, but you can specify a different value for each of them using the paper_bgcolor and plot_bgcolor keys respectively.

You can also specify the title and different font properties for all the axes in your chart. The font properties are nested inside the axis keys for the respective axes. You also have the ability to independently control the base color for the axis and the color of the font used for its title.

Sometimes, the points being plotted on a chart don't go all the way down to zero. In such cases, the ticks created by Plotly on an axis also don't extend to zero. However, if you want the ticks to always start from zero, regardless of the range of points being plotted, you can use the rangemode attribute and set its value to tozero.

The following code snippet uses some of the attributes we just discussed to modify the appearance of the chart we created in the previous section.

1
const lineDiv = document.getElementById('line-chart');
2
3
const traceA = {
4
  x: [25, 30, 35, 40, 45, 50, 55],
5
  y: [40, 40, 20, 60, 40, 20, 50],
6
  type: 'scatter'
7
};
8
9
const data = [traceA];
10
11
const layout = {
12
  title:'A Line Chart in Plotly',
13
  height: 550,
14
  font: {
15
    family: 'Lato',
16
    size: 16,
17
    color: 'rgb(100,150,200)'
18
  },
19
  plot_bgcolor: 'rgba(200,255,0,0.1)',
20
  margin: {
21
    pad: 10
22
  },
23
  xaxis: {
24
    title: 'Distance travelled along x-axis',
25
    titlefont: {
26
      color: 'black',
27
      size: 12
28
    },
29
    rangemode: 'tozero'
30
  },
31
  yaxis: {
32
    title: 'Distance travelled along y-axis',
33
    titlefont: {
34
      color: 'black',
35
      size: 12
36
    },
37
    rangemode: 'tozero'
38
  }
39
};
40
41
Plotly.newPlot( lineDiv, data, layout );

Conclusion

In this tutorial, you learned about various features of the Plotly.js library. I also covered the installation and usage of the library along with different layout attributes to customize the appearance of the charts according to your needs.

This post has been updated with contributions from Jacob Jackson. Jacob is a web developer, technical writer, freelancer, and open-source contributor.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.