Search code examples
pythonboxplotaltair

Align rotated labels of Altair boxplot


I'm plotting a boxplot graph using Altair to divide the data into groups (similar to what was done here: Altair boxplot with nested grouping by two categorical variables) . The code I have is below:

import seaborn as sns
import altair as alt

tips = sns.load_dataset("tips")

tips = tips.replace('Sun', 'Sunday morning')

chart = alt.Chart(tips).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','Sunday morning'],header=alt.Header(labelPadding=-530,labelAngle=-90))
).properties(
    width=80,
    height = 350
).configure_view(
    stroke=None
)

However, I can not manage to properly position the column labels after rotating them 90 degrees. In the image below, you can see the graph I'm getting in 'a', and the graph I would like to get in 'b'.

enter image description here

I looked for configurations on https://altair-viz.github.io/user_guide/configuration.html, but could not find a solution. Does anyone have an idea? (I'm using Altair 4.2.2 - the latest version).


Solution

  • I have tried various parameters, referring to this answer. I got the intended result by setting the label orient to bottom and modifying the padding. I don't have as much experience with Altair as you describe.

    import seaborn as sns
    import altair as alt
    
    tips = sns.load_dataset("tips")
    
    tips = tips.replace('Sun', 'Sunday morning')
    
    chart = alt.Chart(tips).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','Sunday morning'],
                          header=alt.Header(
                              labelPadding=360,
                              labelAngle=-90,
                              orient='bottom',
                              labelOrient='bottom',
                              labelAlign='right'
                              
                          ))
    ).properties(
        width=80,
        height = 350
    ).configure_view(
        stroke=None
    )
    chart
    

    enter image description here