Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to save multiple plots into a single HTML file in Python Plotly?
Plotly is an open-source Python library for creating interactive charts. You can use the plotly.subplots feature to save multiple plots into a single HTML file, which is useful for creating dashboards or comparing different visualizations.
Using make_subplots to Create Multiple Plots
The make_subplots function allows you to create a grid of subplots within a single figure. Here's how to create and save multiple plots to an HTML file ?
import plotly
from plotly.subplots import make_subplots
import plotly.graph_objects as go
# Create subplots with 2 rows and 1 column
fig = make_subplots(rows=2, cols=1,
subplot_titles=('First Plot', 'Second Plot'))
# Add first scatter plot to row 1
fig.add_trace(go.Scatter(x=[0, 1, 2], y=[5, 6, 7],
name='Dataset 1'), row=1, col=1)
# Add second scatter plot to row 2
fig.add_trace(go.Scatter(x=[7, 8, 9], y=[20, 21, 22],
name='Dataset 2'), row=2, col=1)
# Update layout
fig.update_layout(height=600, width=700,
title_text="Multiple Plots in Single HTML")
# Save to HTML file
plotly.offline.plot(fig, filename='multiple_plots.html')
print("HTML file 'multiple_plots.html' has been created!")
HTML file 'multiple_plots.html' has been created!
Creating Different Types of Plots
You can combine different plot types in the same HTML file ?
import plotly
from plotly.subplots import make_subplots
import plotly.graph_objects as go
# Create a 2x2 subplot grid
fig = make_subplots(rows=2, cols=2,
subplot_titles=('Scatter Plot', 'Bar Chart',
'Line Plot', 'Histogram'))
# Add scatter plot
fig.add_trace(go.Scatter(x=[1, 2, 3, 4], y=[10, 11, 12, 13],
mode='markers'), row=1, col=1)
# Add bar chart
fig.add_trace(go.Bar(x=['A', 'B', 'C'], y=[1, 3, 2]),
row=1, col=2)
# Add line plot
fig.add_trace(go.Scatter(x=[1, 2, 3, 4], y=[4, 5, 6, 7],
mode='lines'), row=2, col=1)
# Add histogram
fig.add_trace(go.Histogram(x=[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]),
row=2, col=2)
# Update layout
fig.update_layout(height=600, width=800,
title_text="Different Plot Types", showlegend=False)
# Save to HTML
plotly.offline.plot(fig, filename='mixed_plots.html')
print("Mixed plots saved to 'mixed_plots.html'")
Mixed plots saved to 'mixed_plots.html'
Key Parameters
| Parameter | Description | Example |
|---|---|---|
rows, cols |
Grid dimensions | rows=2, cols=2 |
subplot_titles |
Individual plot titles | ['Plot 1', 'Plot 2'] |
filename |
Output HTML file name | 'dashboard.html' |
Conclusion
Use make_subplots() to combine multiple Plotly charts into a single HTML file. This approach is perfect for creating interactive dashboards that can be easily shared and viewed in any web browser.
Advertisements
