简体   繁体   中英

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. i read another question that have my problem, that say problem is the version of altair but i'm in last one.

The warning in the javascript console tells you why this isn't working:

[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. 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

在此处输入图像描述

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