pythonpandasaltair

Setting order of categorical columns in Altair histogram


Trying to swap order of columns in histogram.

data = {'Age group': {0: '0 - 4', 1: '12 - 16', 2: '5 - 11', 3: 'not specified'},
 'Count': {0: 81.0, 1: 86.0, 2: 175.0, 3: 0.0}}

dp = pd.DataFrame(data)

alt.Chart(dp).mark_bar().encode(
    x=alt.X('Age group:N', title='Age group'),
    y='Count:Q',
    tooltip=['Age group', 'Count']
).properties(title='Number of children in voucher', width=400)

enter image description here

Just want to swap the order and can't find a way of doing it.


Solution

  • The Alt.X schema has a sort parameter that accepts an array specifying the field values in preferred order :

    X_ORDER = ["0 - 4", "5 - 11", "12 - 16", "not specified"] # >> set an order
    
    alt.Chart(dp).mark_bar().encode(
        x=alt.X(
            "Age group:N",
            title="Age group",
            sort=X_ORDER, # >> add this line
        ),
        y="Count:Q",
        tooltip=["Age group", "Count"],
    ).properties(title="Number of children in voucher", width=400)
    

    Output :

    enter image description here