Plotly.js is a high-level, open-source JavaScript charting library built on top of D3.js and WebGL. It allows you to create a wide variety of interactive, publication-quality graphs directly in the browser. Unlike Canvas or raw SVG, Plotly.js provides a declarative API, meaning you describe what you want to plot (data, chart type, layout) and Plotly handles the rendering. This makes it incredibly efficient for creating complex visualizations without writing low-level drawing code.
1. Getting Started with Plotly.js
To use Plotly.js, you’ll need to include its JavaScript library in your HTML file. The easiest way is via a CDN (Content Delivery Network).
HTML
<!DOCTYPE html>
<html>
<head>
<title>Plotly.js Tutorial</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="myChart" style="width:700px;height:450px;"></div>
<script>
// Your JavaScript code for Plotly will go here
</script>
</body>
</html>
You need a div
element with an id
where Plotly.js will render the chart. You can set its initial dimensions using CSS width
and height
properties.
2. The Core Concepts: Data and Layout
Every Plotly.js chart is defined by two main components:
- Data (Traces): This is an array of objects, where each object (called a “trace”) represents a series of data to be plotted. A trace includes the actual data points (
x
,y
,z
arrays), the charttype
(e.g., ‘scatter’, ‘bar’, ‘pie’), and specific properties for that type (e.g.,mode
,marker
for scatter plots). - Layout: This is an object that defines the overall appearance of the chart, such as the title, axis labels, legends, margins, annotations, and more.
3. Your First Plot: A Simple Scatter Plot
Let’s create a basic scatter plot to see how Plotly.newPlot()
works.
JavaScript
// 1. Define your data (traces)
var trace1 = {
x: [1, 2, 3, 4, 5],
y: [10, 11, 12, 13, 14],
mode: 'markers', // 'lines', 'lines+markers', 'text'
type: 'scatter',
name: 'Series A',
marker: {
size: 10,
color: 'rgba(255, 0, 0, 0.7)' // Red with transparency
}
};
var trace2 = {
x: [1.5, 2.5, 3.5, 4.5, 5.5],
y: [8, 10, 12, 14, 16],
mode: 'lines+markers',
type: 'scatter',
name: 'Series B',
line: {
color: 'blue',
width: 2
}
};
var data = [trace1, trace2]; // Array of all traces
// 2. Define your layout
var layout = {
title: 'My First Plotly.js Scatter Plot',
xaxis: {
title: 'X-Axis Label',
gridcolor: '#eee', // Light grey grid lines
gridwidth: 1
},
yaxis: {
title: 'Y-Axis Label',
zerolinecolor: '#ccc', // Grey zero line
zerolinewidth: 2
},
hovermode: 'closest', // Show hover info for the closest point
margin: {
l: 50, r: 50, b: 50, t: 70 // Left, right, bottom, top margins
},
showlegend: true // Display the legend
};
// 3. Render the plot
// Plotly.newPlot(DOM_element_or_ID, data_array, layout_object, optional_config_object)
Plotly.newPlot('myChart', data, layout);
When you open this HTML file in your browser, you’ll see an interactive scatter plot with two series. You can zoom, pan, and hover over data points to see their values.
4. Exploring Other Chart Types
Plotly.js supports a vast array of chart types. You simply change the type
property in your trace object.
a. Bar Chart
JavaScript
var barData = [{
x: ['Apples', 'Oranges', 'Bananas'],
y: [15, 20, 12],
type: 'bar',
marker: {
color: ['green', 'orange', 'yellow']
}
}];
var barLayout = {
title: 'Fruit Sales',
xaxis: { title: 'Fruit' },
yaxis: { title: 'Quantity Sold' }
};
// Plotly.newPlot('myChart', barData, barLayout); // Uncomment to test this chart
b. Pie Chart
JavaScript
var pieData = [{
values: [45, 25, 15, 15],
labels: ['Safari', 'Chrome', 'Firefox', 'Edge'],
type: 'pie',
hoverinfo: 'label+percent', // Show label and percentage on hover
textinfo: 'label+value', // Show label and value inside slices
marker: {
colors: ['#36A2EB', '#FFCE56', '#4BC0C0', '#FF6384']
}
}];
var pieLayout = {
title: 'Browser Market Share',
height: 400,
width: 500
};
// Plotly.newPlot('myChart', pieData, pieLayout); // Uncomment to test this chart
5. Updating Plots
Instead of redrawing the entire plot, you can efficiently update parts of it using Plotly.restyle()
or Plotly.relayout()
for performance.
Plotly.restyle(div, updateObject, traceIndex)
: Changes data or trace-specific attributes.Plotly.relayout(div, updateObject)
: Changes layout attributes.
JavaScript
// Example: Change the color of Series A and the chart title after 3 seconds
setTimeout(function() {
// Update trace1's marker color
Plotly.restyle('myChart', { 'marker.color': 'purple' }, 0); // 0 is the index of trace1
// Update the chart title
Plotly.relayout('myChart', { title: 'Updated Scatter Plot Title' });
}, 3000);
6. Interactivity and Customization
Plotly.js charts are inherently interactive. Users can:
- Pan, zoom, and select regions.
- Toggle traces on/off by clicking legend items.
- Hover over points to see tooltips.
- Download plots as PNGs.
You can customize almost every aspect of a Plotly chart through its extensive layout
and trace
properties, including:
- Axis ranges, ticks, and labels
- Legend position and styling
- Annotations and shapes
- Custom hover text
- Animations (more advanced)
Plotly.js is an excellent choice for creating interactive and dynamic data visualizations on the web, especially when dealing with complex datasets or needing advanced chart types that go beyond basic bar or line graphs. Its declarative API allows you to focus on your data and the story it tells, rather than low-level drawing commands.