Altair Color is overriding / removing sort order

Viewed 151

New user with Altair, trying to sort NFL player names by the "Player COUNT" field. The data is pre-aggregated to show each playername only once, with the count associated to it.

Sorting the y axis which is 'Player Name' based on the count in -x works fine until I add color, which i want to be a discrete dimension. Any idea what needs to be done to prevent color from overriding the sort on Y?

import altair as alt
import pandas as pd

source = pd.read_csv("C:/Users/abcdef/Documents/user_players.csv", encoding = "ISO-8859-1") 
print(source.head())

bars = alt.Chart(source).mark_bar().encode(
    x=alt.X('Player COUNT:Q'),#,scale=alt.Scale(domain=(1,5),clamp=True)),
    y=alt.Y('Player Name:N',sort='-x')
    #y=alt.Y('Player Name:N',sort=alt.SortField(field="sort_order",op="distinct",order='descending')),
    ,color='Ownership Percentile:O'
).transform_filter(
      alt.FieldLTEPredicate(field='player_row', lte=50)
)

text = bars.mark_text(
    align='left',
    baseline='middle',
    dx=3  # Nudges text to right so it doesn't appear on top of the bar
).encode(
    text='Player COUNT:Q'
)

(bars + text).properties(width =400,height=900)#.interactive()

screenshot 1 screenshot 2

1 Answers

This looks like a bug in the Vega-Lite renderer. You can work around it by using an EncodingSortField with an explicit op in place of the -x shorthand:

bars = alt.Chart(source).mark_bar().encode(
    x=alt.X('Player COUNT:Q'),#,scale=alt.Scale(domain=(1,5),clamp=True)),
    y=alt.Y('Player Name:N',sort=alt.EncodingSortField(field="Player COUNT", order='descending', op='max')),
    color='Ownership Percentile:O'
).transform_filter(
      alt.FieldLTEPredicate(field='player_row', lte=50)
)
Related