Setting order of categorical columns in Altair histogram

45 Views Asked by At

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.

2

There are 2 best solutions below

0
Timeless On BEST ANSWER

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

0
joelostblom On

In addition to setting the category order directly in altair via sort, altair is also able to infer the order from the pandas dataframe when you work with categorical data (which can be preferable for other pandas operations as well):

import pandas as pd
import altair as alt


data = pd.DataFrame({
    '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}
})

data['Age group'] = pd.Categorical(
    data['Age group'],
    ['0 - 4', '5 - 11', '12 - 16', 'not specified'],
    ordered=True
)

alt.Chart(data, title='Number of children in voucher', width=200).mark_bar().encode(
    x='Age group',
    y='Count:Q',
    tooltip=['Age group', 'Count']
)

enter image description here