This example demonstrates how to create an interactive scatter plot using Plotly.js, a powerful charting library. Scatter plots are useful for visualizing the relationship between two numerical variables. You can hover over points to see their values, zoom, pan, and download the plot as an image.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Plotly Scatter Plot</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="myPlot"></div>
<script src="script.js"></script>
</body>
</html>
// Sample data for the scatter plot
const trace1 = {
x: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
y: [10, 8, 6, 4, 2, 1, 3, 5, 7, 9],
mode: 'markers',
type: 'scatter',
marker: {
color: 'rgba(255, 0, 0, 0.7)',
size: 12,
line: {
color: 'rgba(0, 0, 0, 0.5)',
width: 1
}
},
name: 'Group A'
};
const trace2 = {
x: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
y: [1, 3, 5, 7, 9, 10, 8, 6, 4, 2],
mode: 'markers',
type: 'scatter',
marker: {
color: 'rgba(0, 0, 255, 0.7)',
size: 10,
line: {
color: 'rgba(0, 0, 0, 0.5)',
width: 1
}
},
name: 'Group B'
};
const data = [trace1, trace2];
const layout = {
title: 'Example Scatter Plot of Two Groups',
xaxis: {
title: 'X-Axis Label'
},
yaxis: {
title: 'Y-Axis Label'
},
hovermode: 'closest',
margin: { t: 40, b: 40, l: 40, r: 40 },
plot_bgcolor: '#f8f8f8',
paper_bgcolor: '#ffffff',
font: {
family: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
size: 12,
color: '#333'
}
};
Plotly.newPlot('myPlot', data, layout);
1. Include Plotly.js: The Plotly.js library is included via a CDN link in the <head> of the HTML document. This makes the charting functions available.
2. HTML Structure: A <div> element with a unique ID (e.g., myPlot
) is created. This div will serve as the container for the plot.
3. JavaScript Data and Layout: In the JavaScript file (or within a <script> tag), we define the data for our plot.
type: 'scatter'
and mode: 'markers'
are used.marker
object controls the appearance of the points (color, size, border).Plotly.newPlot('myPlot', data, layout);
function call takes the ID of the container div, the data array, and the layout object to render the interactive plot.
Plotly offers extensive customization. You can modify: