Plotly allows you to create interactive, publication-quality figures in Python. You can customize the width and height of your figures through multiple approaches: using update_layout, Plotly Express parameters, default templates, or configuration options when exporting. This guide covers each method with code examples.
1. Using update_layout
The most direct method is setting the width and height properties on the figure’s layout.
import plotly.graph_objects as go
fig = go.Figure(data=go.Scatter(x=[1,2,3], y=[4,1,3]))
fig.update_layout(
width=800, # width in pixels
height=400 # height in pixels
)
fig.show()
2. Specifying Size in Plotly Express
Plotly Express functions accept width and height arguments directly.
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length",
width=900, height=500,
title="Iris Sepal Dimensions")
fig.show()
3. Setting Default Figure Dimensions via Template
Create a custom template with default layout.width and layout.height so you don’t need to specify size on every figure.
import plotly.io as pio
# Define template
pio.templates["my_size_template"] = pio.templates["plotly"].update({
"layout": {
"width": 700,
"height": 350
}
})
pio.templates.default = "my_size_template"
# Now all figures use the default size
import plotly.express as px
fig = px.line(px.data.gapminder(), x="year", y="lifeExp", color="country")
fig.show()
4. Configuring Exported HTML
When exporting to HTML or static images, you can specify size in write_html or write_image calls.
# Export to standalone HTML with fixed size
fig.write_html("chart.html", include_plotlyjs="cdn", full_html=True)
# Export to PNG with desired resolution
fig.write_image("chart.png", width=1200, height=600, scale=2)
5. Responsive and Container-Based Sizing
For web apps, you may want figures to fill their container’s dimensions. Use the autosize and responsive config options.
fig.update_layout(autosize=True)
fig.show(config=dict(responsive=True))
Comparison of Methods
| Method | When to Use | Example |
|---|---|---|
fig.update_layout |
One-off size changes per figure | width=800, height=400 |
Plotly Express width,height |
Quick size for PX charts | px.scatter(..., width=900, height=500) |
| Default template | Consistent sizing across project | Custom layout.width/height in template |
| Export config | Fixed size for saved files | write_image(..., width, height) |
| Responsive | Web apps with flexible layouts | autosize=True, responsive=True |
Summary Checklist
- Use
fig.update_layout(width, height)for individual figures. - Pass
widthandheightto Plotly Express functions. - Create a default-size template for consistent sizing.
- Specify size when exporting HTML or images.
- Enable
autosizeandresponsivefor dynamic layouts in web apps.
