Sorting an Altair Ridgeline Plot

59 Views Asked by At

Here is an example of an Altair Ridgeline Plot. Source:Altair Gallery. How do I sort the ridgeline plot by the max height or area of each ridge in descending order? Is that possible? I want to show the biggest ridges in the top and the smaller ones at the bottom.

import altair as alt
from vega_datasets import data

source = data.seattle_weather.url

step = 20
overlap = 1

alt.Chart(source, height=step).transform_timeunit(
    Month='month(date)'
).transform_joinaggregate(
    mean_temp='mean(temp_max)', groupby=['Month']
).transform_bin(
    ['bin_max', 'bin_min'], 'temp_max'
).transform_aggregate(
    value='count()', groupby=['Month', 'mean_temp', 'bin_min', 'bin_max']
).transform_impute(
    impute='value', groupby=['Month', 'mean_temp'], key='bin_min', value=0
).mark_area(
    interpolate='monotone',
    fillOpacity=0.8,
    stroke='lightgray',
    strokeWidth=0.5
).encode(
    alt.X('bin_min:Q')
        .bin('binned')
        .title('Maximum Daily Temperature (C)'),
    alt.Y('value:Q')
        .axis(None)
        .scale(range=[step, -step * overlap]),
    alt.Fill('mean_temp:Q')
        .legend(None)
        .scale(domain=[30, 5], scheme='redyellowblue')
).facet(
    row=alt.Row('Month:T')
        .title(None)
        .header(labelAngle=0, labelAlign='left', format='%B')
).properties(
    title='Seattle Weather',
    bounds='flush'
).configure_facet(
    spacing=0
).configure_view(
    stroke=None
).configure_title(
    anchor='end'
)

I tried using the class altair.EncodingSortField(field=‘value’, op=count, order=descending) in the y axis. However, that distorts the shapes of the ridges.

1

There are 1 best solutions below

0
joelostblom On

Note that the densities are created in separate faceted rows, so you need to sort the rows rather than the Y-axis. You can do that by appending this to the facet row encoding:

.sort(field='value', op='max', order='descending')