Search code examples
pythonaltairvega-lite

Make collective title for columned Altair chart


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!


Solution

  • 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