5

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()

enter image description here

C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134

2 Answers2

7

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)
Seriously
  • 884
  • 1
  • 11
  • 25
  • much nicer than the other answer – adiro Jun 07 '21 at 17:36
  • Nice, looks like this became available with v4.12 in Oct 2020. – C8H10N4O2 Jun 07 '21 at 23:35
  • 1
    Is there a way to select the specific `col` by name ? So in that example, to pass `col="Sat"` ? – quant Apr 19 '22 at 11:00
  • According to the [documentation](https://plotly.com/python-api-reference/generated/plotly.graph_objects.Figure.html#plotly.graph_objects.Figure.add_trace) `row`/`col` take either `all` or an ID. Not sure how to get the ID from the name though. – Seriously Apr 19 '22 at 12:01
4

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)
kmader
  • 1,319
  • 1
  • 10
  • 13