简体   繁体   中英

add a trace to every facet of a plotly figure

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

在此处输入图像描述

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM