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

Viewed 885
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.

1 Answers

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

enter image description here

Related