Plotly.js is a
library ideally suited for JavaScript applications which make use of graphs and charts. There are a few reasons to consider using it for your next data visualization project:
Plotly.js uses both D3.js (SVG) and WebGL for graphics rendering
Plotly.js is an “all-in-one bundle” with d3.js and stack.gl modules
It works with JSON schema
Plotly.js supports basic, statistical, scientific, financial and map charts.
Also, more than 9000 stars on its open source Github is a strong indicator for its community growth.
Usage and Examples
Let’s
looks at setup and few examples for better and practical understanding.
First, include the file from its CDN.
Next, let’s plot a small graph which shows the numbers and their squares:
The code to generate this graph is below:
Basic setup can be done with a file inclusion, a DOM element, and a script for plotting.
After the inclusion of the Plotly.js library in , we have defined an empty
to plot the graph.
Plotly.new()draws a new plot in the
element, overwriting any existing plotand in this case we used myDiv. The input will be a
element and some data.
Notice the inclusion of mode in the trace variable. It can be any combination of "lines", "markers", "text" joined with a "+" OR "none".
Examples include "lines", "markers", "lines+markers", "lines+markers+text", "none".
Here we have used markers. Notice that you only get points marked in the graph coordinates anddo not see the connected line across all points.
Plot multiple lines now just by adding values to the data variable:
The legendin a graph is linked to the data being graphically displayed in the plot area of the chart.
As of now we don’t have any labels, and the legend looks like:
Let’s update them by using options such as text,textfont ,textpostion for customization of our data labels. These should be passed with individual data sets.
The layout of other visual attributes such as the title and annotations will be defined in an object usually called layout.
By now we have seen some examples of line, let’s quickly plot a bar chart using 'bar' as type.
var data = [{ x: ['Company X', 'Company Y', 'Company Z'], y: [200, 140, 230], type: 'bar' }];Plotly.newPlot('myDiv', data);
You can also change the typein the above data shown for products and mobile by changing scatter to bar.
Now we have data, layout, token and map… Here’s the end result:
This was a plotting demonstration with step by step approach on plotting a map dataset using plotly.js. You can find a
lot of examples on the Plotly documentation to get started with.
Hope this gave you a good introduction to Plotly js.
Make sure to drop your feedback below, and code for this can be found on my Github.