How to group together boxes of different traces for subplots in plotly?

Viewed 214

In the documentation about plotly boxes we are told that for Group Box plots we use boxmode so that to group together boxes for each value x

fig.update_layout(
    yaxis_title='normalized moisture',
    boxmode='group' # group together boxes of the different traces for each value of x
)

My question is how do you apply this in case you are using Box subplots? An example would be nice.

In my case I have 5 box subplots and I have put boxmode in the layout but this affects all subplots, even the ones that have only one trace for each value of x, which gives a weird appearance to the plot.

Related to this, if you have 5 box subplots with only one trace for x value, the boxmode option affects the plots anyway

1 Answers
  • extending https://plotly.com/python/box-plots/#grouped-box-plots example to do sub plots
  • this does work, however it does offset x-axis in subplots (either as rows or columns)
  • have tried setting various xaxis layout parameters to prevent offsetting without success
  • is this the behaviour you are noting does not work well in sub-plots?
import itertools
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np

x = ['day 1', 'day 1', 'day 1', 'day 1', 'day 1', 'day 1',
     'day 2', 'day 2', 'day 2', 'day 2', 'day 2', 'day 2']

fig = make_subplots(rows=1, cols=3)
for r,n in itertools.product(range(3), ["kale","carrots","radishes"]):
    fig.add_trace(go.Box(x=[f"{xx}.{r}" for xx in x], y=np.random.uniform(0,1, len(x)), name=f"{n}-{r}"), row=1, col=r+1)
    
fig.update_layout(boxmode="group")
fig.show()

fig = make_subplots(rows=3, cols=1)
for r,n in itertools.product(range(3), ["kale","carrots","radishes"]):
    fig.add_trace(go.Box(x=[f"{xx}.{r}" for xx in x], y=np.random.uniform(0,1, len(x)), name=f"{n}-{r}"), row=r+1, col=1)
    
fig.update_layout(boxmode="group")

enter image description here

Related