Almost every chart needs tweaks after creation, and these update methods are the standard way to make them.
Plotly figures are edited after creation through update_* methods that take keyword arguments and return the figure, so they chain:
fig.update_layout(title_text="Revenue", height=400, legend_title_text="Region")
fig.update_xaxes(title_text="Month", tickangle=-45)
fig.update_yaxes(tickprefix="$", tickformat=",.0f", rangemode="tozero")Magic underscores let you reach nested attributes in one keyword: title_font_size=20 is the same as title=dict(font=dict(size=20)). Updates are merged, not replaced, so changing title_font_size keeps the title text.
update_xaxes and update_yaxes apply to all axes at once, which matters for faceted figures with many axes; pass row=, col= or selector= to target some of them.
Frequently used settings:
- axes:
range=[lo, hi],type="log",tickformat(d3-format, e.g.".1%",",.0f"),dtick,showgrid,zeroline,matches=Noneto unlink facet axes; - legend:
orientation="h",x,y,xanchor,yanchor,showlegend=False; margin=dict(l=40, r=20, t=50, b=40),width,height;hovermode="x unified"for one tooltip listing all traces at an x.
Assigning attributes directly also works: fig.layout.title.text = "Revenue".
Example
import plotly.express as px
df = px.data.stocks()
fig = px.line(df, x="date", y=["GOOG", "MSFT"])
(fig.update_layout(title_text="Stocks normalized to 1 at start",
title_font_size=20, legend_title_text="Ticker",
legend=dict(orientation="h", y=1.02, x=0, yanchor="bottom"),
hovermode="x unified", height=420)
.update_xaxes(title_text=None, dtick="M3", tickformat="%b %Y")
.update_yaxes(tickformat=".0%", title_text="Relative price"))
print(fig.layout.title.text) # Stocks normalized to 1 at start
print(fig.layout.title.font.size) # 20
print(fig.layout.yaxis.tickformat) # .0%
fig.write_html("stocks.html")Remember
update_layout,update_xaxes,update_yaxesmerge changes and chain- Magic underscores reach nested attributes:
title_font_size=20 - Tick formats use d3-format strings such as
,.0fand.1%
Watch out for
- Calling
fig.update_layout(xaxis_range=...)on a faceted figure and only changing the first panel; useupdate_xaxes.