Reputation: 19015
I'd like to add a trace to all facets of a plotly plot.
For example, I'd like to add a reference line to each daily facet of a scatterplot of the "tips" dataset showing a 15% tip. However, my attempt below only adds the line to the first facet.
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
df = px.data.tips()
ref_line_slope = 0.15 # 15% tip for reference
ref_line_x_range = np.array([df.total_bill.min(), df.total_bill.max()])
fig = px.scatter(df, x="total_bill", y="tip",facet_col="day", trendline='ols')
fig = fig.add_trace(go.Scatter(x=reference_line_x_range,y=ref_line_slope*reference_line_x_range,name='15%'))
fig.show()
Upvotes: 7
Views: 7047
Reputation: 1000
According to an example from plotly you can pass 'all'
as the row
and col
arguments and even skip empty subplots:
fig.add_trace(go.Scatter(...), row='all', col='all', exclude_empty_subplots=True)
Upvotes: 9
Reputation: 1369
It's not an elegant solution, but it should work for most cases
for row_idx, row_figs in enumerate(fig._grid_ref):
for col_idx, col_fig in enumerate(row_figs):
fig.add_trace(go.Scatter(...), row=row_idx+1, col=col_idx+1)
Upvotes: 4