Keeping specific Y-Axis order/sort in Altair for Layered Charts

Viewed 2081

I wanted to build on Trellis Plot shown in Altair documentation here: https://altair-viz.github.io/gallery/beckers_barley_trellis_plot.html.

In the code shown below, I am creating "mark_rule" chart with specific Y-Axis sorting and layering it with "mark_point" in order to highlight end points. However, when I add "mark_point" layer on top of "mark_rule" , the Y-Axis sort/order is lost; and I cannot re-sort/reorder the Y-Axis of the layered chart. Please see below "mark_rule" plot that has proper Y-Axis sorting and "mark_rule + park_point" chart, where the Y-Axis sort is lost after the layering. I was wondering how we can re-cover the Y-Axis sort after layering. Adding final "encode" for Y-Axis sorting does not seem to help.

combined = alt.layer(rule, point_a, point_b).encode(alt.Y('key:N', axis=alt.Axis(title='', grid=True),sort=alt.EncodingSortField(field='item_b', op='max', order='descending')))

Below is the reproducible code for the images attached:

df = pd.DataFrame(
[
    {
        'key': 'US',
        'item_a': 1.14,
        'item_b': 1.43
    },
    {
        'key': 'IN',
        'item_a': 0.78,
        'item_b': 0.88
    },
    {
        'key': 'CN',
        'item_a': 0.38,
        'item_b': 0.44
    },
    {
        'key': 'AE',
        'item_a': 0.19,
        'item_b': 0.22
    },    
    {
        'key': 'MX',
        'item_a': 0.95,
        'item_b': 0.99
    },  
    {
        'key': 'RU',
        'item_a': 0.57,
        'item_b': 0.63
    }, 
    {
        'key': 'SA',
        'item_a': 0.52,
        'item_b': 0.49
    },     
    {
        'key': 'TR',
        'item_a': 0.29,
        'item_b': 0.34
    },      
]
)

base = alt.Chart(data=df, title='').encode(
    alt.Y('key:N', axis=alt.Axis(title='', grid=True),sort=alt.EncodingSortField(field='item_b', op='max', order='descending'))
)
rule = base.mark_rule(color='gray').encode(
    alt.X('item_a:Q', axis=alt.Axis(grid=False, title="Value")),
    alt.X2('item_b'),    
)
# rule.save('Just_rule.png', scale_factor=2)
point_a = base.mark_point(color='red', size=80).encode(alt.X('item_a'))
point_b = base.mark_point(color='steelblue', size=80).encode(alt.X('item_b'))
# combined.save('Combined.png', scale_factor=2)

mark_rule with proper Y-Axis ordering

mark_rule + mark_point with Y-Axis ordering lost

1 Answers

This is a known bug in sorting + layering within Altair/Vega-Lite. It has been fixed upstream in Vega-Lite (see vega-lite#2177), so your code should work correctly once Altair 3.0 is released. In the meantime, you might be able to use the workaround mentioned here.

Related