Make collective title for columned Altair chart

Viewed 145

Good day!

I have this dataset from which I make a columned bar chart.

d = {'year': [2015, 2015, 2015, 2016, 2016, 2016, 2017, 2017, 2017], 
     'num_pupils': [352, 365, 369, 438, 440, 456, 582, 584, 602], 
     'school_name': ["Brentwood", "Underburg", "Mary's House", 
                     "Brentwood", "Underburg", "Mary's House", 
                     "Brentwood", "Underburg", "Mary's House"]}

df = pd.DataFrame(data=d)

chart = alt.Chart(df).mark_bar().encode(
            alt.X('num_pupils:Q', title="No. of pupils"),
            alt.Y('year:N', title="Year", sort='descending'), 
            alt.Column('school_name:N', title= None)
        ).properties(
            title="Number of pupils per school from 2015 to 2017",
            width=250,
            height=250
        )

The chart then looks like this: Chart

At the bottom, where "No. of pupils" is repeated for each column - I want to have a single heading and remove the duplication. Is there a way to do this?

All help is appreciated, thanks!

2 Answers

You could use the column header for this purpose like this:

chart = alt.Chart(df).mark_bar().encode(
            alt.X('num_pupils:Q', title=None),
            alt.Y('year:N', title="Year", sort='descending'), 
            alt.Column('school_name:N', header=alt.Header(title='No. of pupils', titleOrient='bottom')),
        ).properties(
            title="Number of pupils per school from 2015 to 2017",
            width=250,
            height=250
        )

plot

Edit: See debbes answer for an easier workaround (if you don't need the column header for the facets).

This is currently not supported but you can workaround it by manually placing a text_mark as in Can I turn altair axis titles into links?:

chart = alt.Chart(df).mark_bar().encode(
            alt.X('num_pupils:Q', title=""),
            alt.Y('year:N', title="Year", sort='descending'), 
            alt.Column('school_name:N', title= None)
        ).properties(
            title="Number of pupils per school from 2015 to 2017",
            width=250,
            height=250
        )
text = alt.Chart().mark_text(
    align="center",
    baseline="bottom",
    fontSize=11,
    fontWeight=600,
    dx=390,
    dy=0,
).encode(
    text=alt.value("No. of pupils")
)

(chart & text).configure_view(stroke=None)

enter image description here

Related