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
How to plot multiple figures as subplots in Python Plotly?
Plotly is an open-source Python library for creating interactive charts. You can use the make_subplots feature available in Plotly to combine multiple figures into subplots within a single layout.
In this tutorial, we will use plotly.graph_objects and plotly.subplots to create multiple subplots. The make_subplots() function allows you to specify the grid layout, while append_trace() adds individual plots to specific positions.
Basic Subplot Creation
Here's how to create a simple subplot layout with three scatter plots ?
from plotly.subplots import make_subplots
import plotly.graph_objects as go
# Create subplot grid: 3 rows, 1 column
fig = make_subplots(rows=3, cols=1)
# Add first scatter plot to row 1
fig.append_trace(go.Scatter(
x=[1, 2, 3, 4, 5],
y=[5, 6, 7, 8, 9],
name='Plot 1'
), row=1, col=1)
# Add second scatter plot to row 2
fig.append_trace(go.Scatter(
x=[3, 4, 5, 6, 7],
y=[10, 11, 12, 9, 8],
name='Plot 2'
), row=2, col=1)
# Add third scatter plot to row 3
fig.append_trace(go.Scatter(
x=[4, 5, 6, 7, 8],
y=[6, 7, 8, 9, 10],
name='Plot 3'
), row=3, col=1)
# Update layout
fig.update_layout(height=600, title_text="Multiple Subplots Example")
fig.show()
Multiple Columns Layout
You can also create subplots with multiple rows and columns ?
from plotly.subplots import make_subplots
import plotly.graph_objects as go
# Create 2x2 subplot grid
fig = make_subplots(
rows=2, cols=2,
subplot_titles=('Plot 1', 'Plot 2', 'Plot 3', 'Plot 4')
)
# Top-left
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1)
# Top-right
fig.add_trace(go.Bar(x=['A', 'B', 'C'], y=[1, 3, 2]), row=1, col=2)
# Bottom-left
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[2, 4, 3]), row=2, col=1)
# Bottom-right
fig.add_trace(go.Bar(x=['X', 'Y', 'Z'], y=[3, 1, 4]), row=2, col=2)
fig.update_layout(height=500, title_text="2x2 Subplot Grid")
fig.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
rows |
Number of rows in subplot grid | rows=3 |
cols |
Number of columns in subplot grid | cols=2 |
subplot_titles |
Titles for each subplot | subplot_titles=('Plot 1', 'Plot 2') |
row, col |
Position where to add the trace | row=1, col=2 |
Conclusion
Use make_subplots() to create grid layouts and append_trace() or add_trace() to position plots. This approach allows you to combine different chart types and create comprehensive dashboard-style visualizations in Plotly.
