How do you center mark text in a bar stack?

Below is a snippet of my code:

bar_chart = alt.Chart(pd_df_chart, title='Number of Carriers by Year and A/P Term(s)').mark_bar().encode(
                alt.X('DELIVERED_YEAR:O', title='Delivery Year'),
                alt.Y('sum(CARRIER_COUNT):Q', title='Number of Carriers'),
                alt.Color('TERMS:N', title='Carrier Terms')
            )
            bar_text = alt.Chart(pd_df_chart).mark_text(baseline='middle',color='white').encode(
                x=alt.X('DELIVERED_YEAR:O', title='Delivery Year'),
                y=alt.Y('sum(CARRIER_COUNT):Q', title='Number of Carriers'),
                detail=alt.Color('TERMS:N', title='Carrier Terms'),
                text=alt.Text('sum(CARRIER_COUNT):Q', format='n')
            )
            st.altair_chart(bar_chart + bar_text, use_container_width=True)

I can’t get the numbers to center on the corresponding stack in the bars. Any advise would be helpful.

I am getting closer:

bar_chart = alt.Chart(pd_df_chart, title='Number of Carriers by Year and A/P Term(s)').mark_bar().encode(
                alt.X('DELIVERED_YEAR:O', title='Delivery Year'),
                alt.Y('sum(CARRIER_COUNT):Q', title='Number of Carriers', stack='zero'),
                alt.Color('TERMS:N', title='Carrier Terms')
            )
            bar_text = alt.Chart(pd_df_chart).mark_text(align='center',baseline='line-top',color='white').encode(
                x=alt.X('DELIVERED_YEAR:O'),
                y=alt.Y('sum(CARRIER_COUNT):Q', stack='zero'),
                detail='TERMS:N',
                text=alt.Text('sum(CARRIER_COUNT):Q', format='d')
            )
            st.altair_chart(bar_chart + bar_text, use_container_width=True)

However, I still happen figured out how to center the mark text stack.

You need to calculate new coordinates for text - > add transform_calculate and divide a bar height by 2, that way labels will be in the middle of your bars.

bar_chart = alt.Chart(source, title='Number of Carriers by Year and A/P Term(s)').mark_bar().encode(
                alt.X('a:O', title='Delivery Year'),
                alt.Y('b:Q', title='Number of Carriers', stack='zero'),
                alt.Color('a:N', title='Carrier Terms')
            )
bar_text = alt.Chart(source).mark_text(align='center',baseline='line-top',color='white').transform_calculate(
    text_mid = '(datum.b/2)').encode(
                x=alt.X('a:O'),
                y=alt.Y('text_mid:Q', stack='zero'),
                #detail='TERMS:N',
                text=alt.Text('b:Q', format='d')
            )

visualization (30)

2 Likes

Hi, ngolos, my apologies for taking so long to say thank you. Thank you! :slight_smile:

1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.