I am trying to plot grouped boxplots as a grid with data from a data-frame using Plotly. For example if we have a dataframe,
import plotly.express as px
df = px.data.tips()
total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
I can draw a single plot as follows (e.g: for day = Friday):
import plotly.graph_objects as go
import plotly.express as px
df_plot=df[df['day']== 'Fri']
fig = px.box(df_plot, x='time', y="total_bill", color="sex",width=600, height=400)
fig.show()
If I want to draw multiple subplots, for example, one for each day, I am not sure how to do that in plotly. This is what I tried:
fig = make_subplots(rows=2, cols=2)
for v in range(4):
for i, met in enumerate(df['day'].unique()): #'Sun', 'Sat', 'Thur', 'Fri'
df_plot=df[df['day']== met]
for t in px.box(df_plot, x="time", y=f"total_bill", color='sex').data:
fig.add_trace(t, row=(v//2)+1, col=(v%2)+1)
fig.update_layout(
boxmode="group", margin={"l": 0, "r": 0, "t": 20, "b": 0}
).update_traces(showlegend=True)
This gives a weird looking plot. What am I doing wrong? Also, in a grid of subplots with plotly, how can I draw one legend instead of legends for each plots.



