Plotly.js – Interactive JavaScript Charts
Plotly.js is a high-level, open-source JavaScript library for creating interactive, publication-quality charts and dashboards. It’s built on D3.js and Stack.gl, providing smooth interactivity, zooming, hovering, and 3D charts.
Getting Started
1. Include Plotly.js
Via CDN:
<script src="<https://cdn.plot.ly/plotly-latest.min.js>"></script>
Or install via npm:
npm install plotly.js-dist
2. HTML Container
Plotly charts render inside a <div>
:
<div id="myPlot" style="width:600px;height:400px;"></div>
Creating a Basic Plot
Example: Line Chart
<script>
const trace = {
x: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
y: [10, 15, 13, 17, 21],
type: 'scatter', // 'scatter' for line/point charts
mode: 'lines+markers', // lines, markers, or both
name: 'Sales',
line: { color: 'blue' }
};
const data = [trace];
const layout = {
title: 'Monthly Sales Data',
xaxis: { title: 'Month' },
yaxis: { title: 'Revenue' }
};
Plotly.newPlot('myPlot', data, layout);
</script>
Supported Chart Types
Type | Description |
---|---|
Scatter | Line and point plots |
Bar | Vertical or horizontal bars |
Pie | Percentage visualization |
Bubble | Scatter with varying marker size |
Box | Show distribution of data |
Heatmap | Color-coded 2D matrix |
Contour | Smooth gradient lines from 2D data |
3D Scatter | Interactive 3D point charts |
3D Surface | 3D surface plots |
Radar / Polar | Circular data visualizations |
Customizing Charts
Colors & Markers
line: { color: 'red', width: 2 },
marker: { size: 10, color: 'green' }
Layout Options
layout = {
title: 'My Chart',
xaxis: { title: 'X Axis' },
yaxis: { title: 'Y Axis', range: [0, 50] }
};
Hover & Tooltips
hovermode: 'closest' // Shows data on hover
Annotations
annotations: [{
x: 3,
y: 17,
text: 'Peak Value',
showarrow: true,
arrowhead: 2
}]
Updating Charts Dynamically
Plotly.update('myPlot', { y: [[12, 18, 14, 20, 25]] });
Or append new data:
Plotly.addTraces('myPlot', { x: ['Jun'], y: [23], type: 'scatter' });
Advantages of Plotly.js
- Fully interactive charts with zoom, pan, and hover
- Supports 2D and 3D visualizations
- Great for dashboards and data-heavy applications
- Works seamlessly with JSON, arrays, and data from APIs
- Open-source and well-documented
When to Use Plotly.js
- Interactive dashboards
- Scientific and statistical visualizations
- Complex data that requires zooming, tooltips, or 3D representation
- Projects requiring quick integration with JSON or API data