[英]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.我正在尝试使用
mark_text
在堆叠条形图中创建堆叠文本。 I would like to label each bar with the value of 'Time'.我想 label 每个栏的值为“时间”。 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:问题:
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 .
我是这个平台的新手,源代码来自我的笔记本: 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.您应该向文本层添加匹配的
order
编码,以确保文本以相同的顺序显示。
Here is an example of how you can use order
in both charts:以下是如何在两个图表中使用
order
的示例:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.