ericg
ericg

Reputation: 8722

Sorting a stacked bar chart

I can create a stacked bar chart by doing the following:

import pandas as pd
import numpy as np
import altair as alt

data = {'First': {('Header-1', 'H1-A'): 'Red',
                  ('Header-1', 'H1-B'): 'Red',
                  ('Header-1', 'H1-C'): 'Red',
                  ('Header-2', 'H2-A'): 'White',
                  ('Header-2', 'H2-B'): 'White',
                  ('Header-2', 'H2-C'): 'Yellow',
                  ('Header-3', 'H3-A'): 'Red',
                  ('Header-3', 'H3-B'): 'White',
                  ('Header-3', 'H3-C'): 'White',
                  ('Header-3', 'H3-D'): 'Yellow'},
        'Second': {('Header-1', 'H1-A'): 'White',
                   ('Header-1', 'H1-B'): 'Yellow',
                   ('Header-1', 'H1-C'): 'Yellow',
                   ('Header-2', 'H2-A'): 'Yellow',
                   ('Header-2', 'H2-B'): 'Green',
                   ('Header-2', 'H2-C'): 'Green',
                   ('Header-3', 'H3-A'): 'Green',
                   ('Header-3', 'H3-B'): 'Red',
                   ('Header-3', 'H3-C'): 'Red',
                   ('Header-3', 'H3-D'): 'White'},
        'Third': {('Header-1', 'H1-A'): 'Red',
                  ('Header-1', 'H1-B'): 'Green',
                  ('Header-1', 'H1-C'): 'Green',
                  ('Header-2', 'H2-A'): 'Green',
                  ('Header-2', 'H2-B'): 'White',
                  ('Header-2', 'H2-C'): 'White',
                  ('Header-3', 'H3-A'): 'White',
                  ('Header-3', 'H3-B'): 'Green',
                  ('Header-3', 'H3-C'): 'Green',
                  ('Header-3', 'H3-D'): 'Yellow'},        
       }
df = pd.DataFrame(data)
column_counts = df.apply(pd.Series.value_counts).fillna(0)
column_counts[column_counts.columns] = column_counts[column_counts.columns].astype('int64')
unstacked = pd.DataFrame(column_counts.unstack())
unstacked = unstacked.reset_index()
unstacked.columns = ['category','kind','counts']
alt.Chart( unstacked ).mark_bar().encode(
    x='category',
    y='sum(counts)',
    color='kind'
)

I do have some control over the order of the stacks by doing:

alt.Chart( unstacked ).mark_bar().encode(
    x='category',
    y='sum(counts)',
    color='kind',
    order=alt.Order(
      'kind',
      sort='descending'
    )
)

However, the sort parameter of alt.Order only accepts 'ascending' or 'descending'. I would like to customize the order to be Green, Yellow, Red, White.

Is this possible? How?

Upvotes: 6

Views: 2359

Answers (1)

jakevdp
jakevdp

Reputation: 86300

There's no way to directly supply a custom stack order, aside from basing it on descending or ascending order of another field. But you can customize this by providing a field with your desired order.

This can be done with a calculate transform in the chart spec (the vega-lite version of this approach for stack order is outlined here) or by pre-processing the data in Pandas.

Here's an example of the preprocessing approach:

unstacked['order'] = unstacked['kind'].replace(
    {val: i for i, val in enumerate(['Green', 'Yellow', 'Red', 'White'])}
)

alt.Chart( unstacked ).mark_bar().encode(
    x='category',
    y='sum(counts)',
    color=alt.Color('kind',
        # optional: make color order in legend match stack order
        sort=alt.EncodingSortField('order', order='descending')
    ),
    order='order',  # this controls stack order
)

enter image description here

Upvotes: 10

Related Questions