在Altair的折线图末添加标签

问题描述 投票:1回答:1

因此,我一直在尝试获取它,因此每行末尾都有一个标签,提供国家名称,然后我可以删除图例。曾尝试过transform_filter,但没有运气。

我从这里使用数据https://ourworldindata.org/coronavirus-source-data,我清理并重整了数据,使其看起来像这样:-

    index   days    date    country value
0   1219    0   2020-03-26  Australia   11.0
1   1220    1   2020-03-27  Australia   13.0
2   1221    2   2020-03-28  Australia   13.0
3   1222    3   2020-03-29  Australia   14.0
4   1223    4   2020-03-30  Australia   16.0
5   1224    5   2020-03-31  Australia   19.0
6   1225    6   2020-04-01  Australia   20.0
7   1226    7   2020-04-02  Australia   21.0
8   1227    8   2020-04-03  Australia   23.0
9   1228    9   2020-04-04  Australia   30.0
import altair as alt

countries_list = ['Australia', 'China', 'France', 'Germany', 'Iran', 'Italy','Japan', 'South Korea', 'Spain', 'United Kingdom', 'United States']

chart = alt.Chart(data_core_sub).mark_line().encode(
                                            alt.X('days:Q'),
                                            alt.Y('value:Q', scale=alt.Scale(type='log')),
                                            alt.Color('country:N', scale=alt.Scale(domain=countries_list,type='ordinal')),    
                                        )

labels = alt.Chart(data_core_sub).mark_text().encode(
                                            alt.X('days:Q'),
                                            alt.Y('value:Q', scale=alt.Scale(type='log')),
                                            alt.Text('country'),
                                            alt.Color('country:N', legend=None, scale=alt.Scale(domain=countries_list,type='ordinal')), 
                                        ).properties(title='COVID-19 total deaths', width=600)


alt.layer(chart, labels).resolve_scale(color='independent')

这是图表所在的当前混乱状态。

enter image description here

我将如何仅显示姓氏的国家?

python pandas label altair
1个回答
0
投票

您可以通过汇总x和y编码来做到这一点。您希望文本最大为x值,因此可以在x中使用'max'聚合。对于y值,您希望y值与最大x值相关联,因此可以使用{"argmax": "x"}聚合。

通过一些文本对齐方式的调整,结果看起来像这样:

labels = alt.Chart(data_core_sub).mark_text(align='left', dx=3).encode(
    alt.X('days:Q', aggregate='max'),
    alt.Y('value:Q', aggregate={'argmax': 'days'}, scale=alt.Scale(type='log')),
    alt.Text('country'),
    alt.Color('country:N', legend=None, scale=alt.Scale(domain=countries_list,type='ordinal')), 
).properties(title='COVID-19 total deaths', width=600)
© www.soinside.com 2019 - 2024. All rights reserved.