Table of Contents
Why Use Plotly.js?
Installing Plotly
Using Plotly to Create a Chart
Layout Attributes to Customize the Charts
Conclusion
Home Web Front-end JS Tutorial Create Interactive Charts Using Plotly.js, Part 1: Getting Started

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

Mar 09, 2025 am 12:19 AM

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:

npm install plotly.js<br>
Copy after login
Copy after login
Copy after login
Copy after login

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:

npm install plotly.js<br>
Copy after login
Copy after login
Copy after login
Copy after login

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:

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

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

https://cdn.plot.ly/plotly-bundleName-2.14.0.min.js<br><br>// Therefore the basic bundle becomes:<br>https://cdn.plot.ly/plotly-basic-2.14.0.min.js<br><br>// and the cartesian bundle becomes:<br>https://cdn.plot.ly/plotly-cartesian-2.14.0.min.js<br>
Copy after login

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 histogram2d, pie, 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<code>scatter, scatter3d<code>scatter3d, surface<code>surface, and mesh3d<code>mesh3d trace modules. The compressed and minified version of this bundle has a size of 354 kB.
  • gl2d: This bundle contains the scatter<code>scatter, scattergl<code>scattergl, pointcloud<code>pointcloud, heatmapgl<code>heatmapgl, contourgl<code>contourgl, and parcoords<code>parcoords trace modules. It has a size of 362.9 kB after minification and compression.
  • mapbox: This bundle contains the scatter<code>scatter and scattermapbox<code>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<code>scatter, bar<code>bar, histogram<code>histogram, pie<code>pie, ohlc<code>ohlc, and candlestick<code>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<code>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:

npm install plotly.js<br>
Copy after login
Copy after login
Copy after login
Copy after login

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.

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

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.

npm install plotly.js<br>
Copy after login
Copy after login
Copy after login
Copy after login
Create Interactive Charts Using Plotly.js, Part 1: Getting Started

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.

The above is the detailed content of Create Interactive Charts Using Plotly.js, Part 1: Getting Started. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles