Altair boxplot with nested grouping by two categorical variables

Viewed 846

How can I reproduce the following graph done in seaborn in altair?

import seaborn as sns
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", hue="smoker",
             data=tips, palette="Set3")

enter image description here

This was my attempt:

import altair as alt
chart = (
alt.Chart(tips)
.mark_boxplot()
.encode(x=alt.X("day"), y=alt.Y("total_bill"), color="smoker")
.interactive()
.properties(width=300))
chart.show()

which gives me this not wanted graph:

enter image description here

1 Answers

Put smoker on the x-axis and use the column facet for the day and play a bit with the padding and spacing:

chart = alt.Chart(df).mark_boxplot(ticks=True).encode(
    x=alt.X("smoker:O", title=None, axis=alt.Axis(labels=False, ticks=False), scale=alt.Scale(padding=1)), 
    y=alt.Y("total_bill:Q"), 
    color="smoker:N",
    column=alt.Column('day:N', sort=['Thur','Fri','Sat','Sun'], header=alt.Header(orient='bottom'))
).properties(
    width=100
).configure_facet(
    spacing=0
).configure_view(
    stroke=None
)
chart

enter image description here

Related