Search code examples
labelbar-chartaltairstacked-bar-chart

Adding text (percentages) to grouped stacked bar chart in altair


I would like to add text (more specifically, percentages or actual values) to each category in my stacked grouped bar chart. enter image description here

Here's my code:

bar = alt.Chart(df1).mark_bar().encode(
    x=alt.X('Week:N', title=None),
    y=alt.Y('sum(Net Gross Booking Value USD):Q',
        axis=alt.Axis(grid=True,title=None)),
    column=alt.Column('Country Name:N', title=None),
    color=alt.Color('Platform Type Name:N',
            scale=alt.Scale(
                range=['#636EFA', '#EF553B','#00CC96'])))
bar

Is there a way to do that?

I have tried this: https://github.com/altair-viz/altair/issues/1570, but I'm still getting an error that a layered graph can't be faceted.


Solution

  • Here is an example using the barley dataset

    
    import altair as alt
    from vega_datasets import data
    
    source = data.barley()
    #using only a few varieties
    source = source.loc[source.variety.isin(['Peatland', 'Svansota', 'Trebi', 'Velvet'])]
    source['yield_pc'] = source.groupby(['year', 'variety'])['yield'].transform(lambda x: x/x.sum())
    
    base = alt.Chart(source).mark_bar().encode(
        y=alt.Y('yield:Q', stack='zero'),
        x=alt.X('variety:N'),
    )
    
    bars = base.encode(
        color='site',
    )
    
    text = base.mark_text(color='black',align='center', baseline='bottom', 
        dy=35).encode(
        text=alt.Text('yield_pc:Q', format='.1%'),
        detail='site:N',
    )
    (bars+text).properties(width=200).facet(column = 'year')
    
    

    enter image description here

    The text placement isn't the best but normally it requires data-specific manual tuning. So, you can do the tuning according to your data.