简体   繁体   English

在 altair 中对带有标记文本的条形图进行排序的问题

[英]problem in sorting bar chart in altair that layered with a mark text

chart_df= alt.Chart(df).mark_bar().encode(
    x = 'value',
    y = alt.Y('name', sort='-x'),
    color = 'variable'
)

for adding the value of each bar as a text i use bellow code, but i lost sorted bars.为了将每个条的值添加为文本,我使用下面的代码,但我丢失了排序条。

chart_df_text = chart_df.mark_text().encode(
    x = 'text_margin_from_bar:Q',
    text = 'human_readable_value:Q',
).transform_calculate(
    human_readable_value = expr.toString(expr.floor(datum.value/10**7)),
    text_margin_from_bar = datum.value + (datum.value/expr.abs(datum.value))*1000000000
    # i have negetive and positive numbers, so for have a space between number and bar, i do this
)

add添加

y = alt.Y('name', sort='-x'),

to the chart_df_text but still i have problem.到 chart_df_text 但我仍然有问题。 i read another question that have my problem, that say problem is the version of altair but i'm in last one.我读了另一个有我的问题的问题,说问题是 altair 的版本,但我在最后一个。

The warning in the javascript console tells you why this isn't working: javascript 控制台中的警告告诉您为什么这不起作用:

[Warning] Dropping sort property {"field":"value","op":"sum"} as unioned domains only support boolean or op "count", "min", and "max".
[Warning] Domains that should be unioned has conflicting sort properties. Sort will be set to true.

You can work around this by using a supported op within your sort.您可以通过在您的排序中使用支持的op来解决此问题。 For example:例如:

import pandas as pd
import altair as alt
from altair import expr, datum

df = pd.DataFrame({
    'value': [-3E9, -4E9, 6E9, 1E10, -8E9],
    'name': ['Bob', 'Sue', 'Tim', 'Ann', 'Bill'],
    'variable': range(5)
})

chart_df= alt.Chart(df).mark_bar().encode(
    x = 'value',
    y = alt.Y('name', sort=alt.EncodingSortField('value', op='min', order='descending')),
    color = 'variable'
)

chart_df_text = chart_df.mark_text().encode(
    x = 'text_margin_from_bar:Q',
    text = 'human_readable_value:Q',
).transform_calculate(
    human_readable_value = expr.toString(expr.floor(datum.value/10**7)),
    text_margin_from_bar = datum.value + (datum.value/expr.abs(datum.value))*1000000000
)

chart_df + chart_df_text

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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