简体   繁体   中英

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

酒吧

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

栏+文字

Issue:

  • The text is not in its proper stack & The order of the text is also wrong.
  • The Y sorting is reset and they are no longer sorted as expected.

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.

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.

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM