search
HomeWeb Front-endJS TutorialCreate 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.

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

npm install plotly.js<br>

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>

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>

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>

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>

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>
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
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor