Reputation: 93
I am trying to build multiple split violin plots based on the plotly documentation example. I am not sure why the violins are so horizontally smushed. I included violinmode='overlay', which is what one other person once suggested, but it doesn't make a difference.
Below is the code I am using
lengthlm = go.Figure()
lengthlm.add_trace(go.Violin(x=lastmonth['agegroup'][lastmonth['type']=='Canine'],
y=lastmonth['lengthyr'][lastmonth['type']=='Canine'],
legendgroup='Canine',
scalegroup='Canine',
name='Canine',
side='negative',
line_color=color_list[1]))
lengthlm.add_trace(go.Violin(x=lastmonth['agegroup'][lastmonth['type']=='Feline'],
y=lastmonth['lengthyr'][lastmonth['type']=='Feline'],
legendgroup='Feline',
scalegroup='Feline',
name='Feline',
side='positive',
line_color=color_list[0]))
lengthlm.update_xaxes(type='category', categoryorder='array', categoryarray=['< 1 Yr','< 5 Yrs',
'< 10 Yrs','< 15 Yrs','15+ Yrs'])
lengthlm.update_traces(meanline_visible=True)
lengthlm.update_layout(violinmode='overlay',
violingap=0,
template=dash_template,
height=400,
width=750,
margin=dict(l=70))
lengthlm.show()
Upvotes: 3
Views: 3330
Reputation: 145
Within your go.Violin
calls, have you explicitly tried setting width
, which specifies the widths of the violins in data coordinate units?
Alternatively, you can attempt using scalemode='width'
which will force all widths within a scalegroup to be the same.
See the docs.
Upvotes: 1
Reputation: 31226
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
# simulate data...
lastmonth = pd.DataFrame(
{
"agegroup": np.random.choice(
["< 1 Yr", "< 5 Yrs", "< 10 Yrs", "< 15 Yrs", "15+ Yrs"], 1000
),
"type": np.random.choice(["Canine", "Feline"], 1000),
}
)
lastmonth = (
lastmonth.groupby(["agegroup", "type"])
.apply(lambda d: d.assign(lengthyr=np.random.uniform(-1, 6, len(d))))
.reset_index(drop=True)
)
lastmonth["agegroup"] = pd.Categorical(
lastmonth["agegroup"],
categories=["< 1 Yr", "< 5 Yrs", "< 10 Yrs", "< 15 Yrs", "15+ Yrs"],
ordered=True,
)
lastmonth = lastmonth.sort_values("agegroup")
fig = (
px.violin(lastmonth, x="agegroup", y="lengthyr", color="type")
.update_layout(violinmode="overlay", violingap=0)
.for_each_trace(
lambda t: t.update(
side="negative" if t.name == "Feline" else "positive", meanline_visible=True
)
)
)
fig
Upvotes: 3