mf

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

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.

You can directly clone the library using the following command and then use the files located in the dist folder.

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

You can also use the Plotly.js CDN and directly link to the library. Generally, you would like to use a compiled and minified file with the latest version of the library. However, you can also link to a specific version of the library in the CDN. Here is an example:

At the time of writing this tutorial, the latest version of the library is 1.28.3. The file size after minifying and compressing the library is 666 kB. The non-minified and uncompressed version has a size of 5.4 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, and finance. You can get the CDN link for these bundles using the following line:

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.

Using Plotly to Create a Chart

Once you have decided 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:

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.

Conclusion

In this tutorial, you learned about different 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. 

JavaScript has become one of the de facto languages of working on the web. It’s not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

In the rest of the series, you will learn about different types of basic charts that can be created using Plotly. I hope you enjoyed the tutorial, and if you have any questions or suggestions, feel free to share them in the comments.

Powered by WPeMatico

Leave a Comment

Scroll to Top