Childream
Childream

Reputation: 53

Stacked text in a stacked bar chart using Altair mark_text

I'm trying to use mark_text to create a stacked text in a stacked bar chart. I would like to label each bar with the value of 'Time'. Is it possible to have text marks in the corresponding stack of a stacked area chart? Here's how I create bar & text chart:

bar = alt.Chart(df_pivot, title = {'text' :'How do people spend their time?', 'subtitle' : 'Average of minutes per day from time-use diaries for people between 15 and 64'}).mark_bar().transform_calculate(
    filtered="datum.Category == 'Paid work'"
).transform_joinaggregate(sort_val="sum(filtered)", groupby=["Country"]
).encode(
    x=alt.X('Time', stack='zero'),
    y=alt.Y('Country', sort=alt.SortField('sort_val', order='descending')),
    color=alt.Color('Category:N', sort=CatOrder),
    order=alt.Order('color_Category_sort_index:Q'),
    tooltip=['Country', 'Category', 'Time']
).interactive()
bar

bar

text = alt.Chart(df_pivot).mark_text(align='center', baseline='middle', color='black').transform_calculate(
    filtered="datum.Category == 'Paid work'"
).transform_joinaggregate(sort_val="sum(filtered)", groupby=["Country"]
).encode(
    x=alt.X('Time:Q', stack='zero'),
    y=alt.Y('Country', sort=alt.SortField('sort_val', order='descending')),
    detail='Category:N',
    text=alt.Text('Time:Q', format='.0f')
)
bar + text

bar+text

Issue:

It's not that I don't understand why I have these issues. I'm new to this platform, the source code via my notebook: https://www.kaggle.com/interphuoc0101/times-use. Thanks a lot.

Upvotes: 3

Views: 2111

Answers (2)

joelostblom
joelostblom

Reputation: 48879

Here is an example of how you can use order in both charts:

import altair as alt
from vega_datasets import data

source=data.barley()

bars = alt.Chart(source).mark_bar().encode(
    x=alt.X('sum(yield):Q', stack='zero'),
    y=alt.Y('variety:N'),
    color=alt.Color('site'),
    order=alt.Order('color_Category_sort_index:Q'),
)

text = alt.Chart(source).mark_text(dx=-15, dy=3, color='white').encode(
    x=alt.X('sum(yield):Q', stack='zero'),
    y=alt.Y('variety:N'),
    detail='site:N',
    text=alt.Text('sum(yield):Q', format='.1f'),
    order=alt.Order('color_Category_sort_index:Q')
)

bars + text

enter image description here

Upvotes: 1

jakevdp
jakevdp

Reputation: 86310

Your bar chart specifies a stack order:

order=alt.Order('color_Category_sort_index:Q'),

You should add a matching order encoding to your text layer to ensure the text appears in the same order.

Upvotes: 1

Related Questions