Plotly Figure Size and Margins

Set the width and height of a Plotly figure, shrink or grow the margins, stop long labels being cut off, size faceted and many-category charts, and export at exact pixel sizes.

Set the size of a Plotly figure in pixels with fig.update_layout(width=600, height=400), or pass width= and height= to any Plotly Express function. Control the space around the plot with fig.update_layout(margin=dict(l=20, r=20, t=60, b=20)).

Quick Example

import pandas as pd
import plotly.express as px

power = pd.DataFrame({
    "source": ["Solar", "Wind", "Hydro", "Geothermal", "Biomass"],
    "gigawatt_hours": [412, 538, 290, 64, 121],
})

fig = px.bar(power, x="source", y="gigawatt_hours", title="Renewable output last quarter",
             width=600, height=360, template="plotly_white",
             color_discrete_sequence=["#16a34a"],
             labels={"source": "", "gigawatt_hours": "GWh"})
fig.update_layout(margin=dict(l=60, r=20, t=60, b=40))
fig.show()

Plotly bar chart of renewable energy output by source, sized 600 by 360 pixels

This figure is 600 by 360 pixels, with 60px above the plot for the title and 60px on the left for the y-axis. The code targets Plotly 6.x.

Default Size and Margins

Setting Default
Width in a notebook or web page Fills the container
Height in a notebook or web page 450px (525px with the notebook renderers)
Static image export 700 × 500px
Margins l=80, r=80, t=100, b=80
Top margin in Plotly Express without a title t=60

width and height are for the whole figure. The plot area is what's left after the margins, so a 400px tall figure with default margins has only 220px for data.

Remove Extra White Space

Small figures, dashboards and subplots usually look better with tight margins. margin=dict(l=0, r=0, t=0, b=0) removes them all.

fig = px.line(x=list(range(1, 13)), y=[31, 34, 33, 39, 44, 47, 52, 51, 58, 61, 66, 72],
              width=600, height=220, template="plotly_white",
              labels={"x": "", "y": ""})
fig.update_layout(margin=dict(l=0, r=0, t=0, b=0), paper_bgcolor="#f1f5f9")
fig.show()

Short line chart with all margins set to zero, where the tick labels still have just enough room

The tick labels didn't get cut off. Axes have automargin on in Plotly's built-in templates, so the margins grow as far as the labels need. The gray paper_bgcolor here shows where the figure ends, which helps when debugging spacing. See plot vs paper background colors.

margin_pad is different: it adds space between the plot area and the tick labels.

Long Labels and Cut-Off Text

With long category names, automargin takes the room out of the plot area:

programs = pd.DataFrame({
    "program": ["Community solar subscription for renters", "Rooftop solar rebate",
                "Heat pump conversion assistance", "Home battery pilot"],
    "households": [1840, 3120, 2675, 410],
})
fig = px.bar(programs.sort_values("households"), x="households", y="program",
             orientation="h", width=700, height=320, template="plotly_white",
             color_discrete_sequence=["#0f766e"], text="households",
             labels={"program": "", "households": "Households enrolled"})
fig.update_traces(textposition="outside", cliponaxis=False)
fig.update_layout(margin=dict(l=10, r=60, t=20, b=50))
fig.show()

Horizontal bar chart of program enrollment where long program names widen the left margin automatically

Two things aren't covered by axis automargin:

  • Text drawn past the plot area, such as outside bar labels. Set cliponaxis=False and leave a right or top margin for it.
  • Annotations placed in the margin. Make the margin large enough by hand. See custom annotations.

If the names take too much width, wrap them: programs["program"].str.wrap(18).str.replace("\n", "<br>").

Keep the Plot Aligned Across Charts

Automatic margins differ from chart to chart, so stacked dashboard panels can end up misaligned. Turn automargin off and use the same fixed margin on each.

fig = px.bar(power, x="source", y="gigawatt_hours", width=600, height=300,
             template="plotly_white", color_discrete_sequence=["#ca8a04"],
             labels={"source": "", "gigawatt_hours": "GWh"})
fig.update_yaxes(automargin=False)
fig.update_layout(margin=dict(l=90, r=20, t=20, b=40))
fig.show()

Bar chart with a fixed 90 pixel left margin and automargin turned off

Scale the Height with the Data

A fixed height squeezes charts with many categories. Compute it from the number of rows.

towns = pd.DataFrame({
    "town": [f"District {n}" for n in range(1, 31)],
    "installs": [(n * 137) % 311 + 40 for n in range(1, 31)],
}).sort_values("installs")

row_height, extra = 22, 110
fig = px.bar(towns, x="installs", y="town", orientation="h",
             height=len(towns) * row_height + extra, width=650,
             template="plotly_white", color_discrete_sequence=["#4f46e5"],
             title="Solar installs in 30 districts", labels={"town": "", "installs": "Installs"})
fig.update_layout(margin=dict(l=10, r=20, t=60, b=50))
fig.show()

Tall sorted horizontal bar chart with 30 districts, each with its own readable row

The same idea works for facets: height=rows * 250, where rows is the number of facet rows. In make_subplots, set the height with update_layout, as covered in the subplots guide.

Responsive Width

Leave width unset and the figure resizes with its container, which is what you want on a web page or in Streamlit and Dash. Set only the height:

fig = px.bar(power, x="source", y="gigawatt_hours", height=350, template="plotly_white")
fig.show(config={"responsive": True})

If a figure doesn't resize after the window changes, check that width isn't set somewhere, including in a template. For shapes that must stay square, see fixed aspect ratios.

Export at an Exact Size and Resolution

write_image takes its own width, height and scale. The pixel size is each dimension times scale.

# writes a 1600 x 900 PNG (needs the kaleido package)
fig = px.bar(power, x="source", y="gigawatt_hours", template="plotly_white")
fig.update_layout(font_size=16)
fig.write_image("power.png", width=800, height=450, scale=2)
fig.show()

Bar chart exported at 800 by 450 with a scale of 2

Increasing scale makes a sharper copy of the same layout. Increasing width and height gives the data more room and makes text look relatively smaller. For print, pick width and height for the layout, then scale for the resolution. Static export with Kaleido covers the other formats.

Set a Default Size for Every Figure

import plotly.io as pio

pio.templates["plotly_white"].layout.update(height=400, margin=dict(l=60, r=30, t=60, b=50))
px.defaults.template = "plotly_white"

px.defaults.width and px.defaults.height do the same for Plotly Express only, and pio.defaults.default_width, default_height and default_scale control exports.

Similar Topics