question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

`sort` argument doesn't sort categories/colors in stacked bar

See original GitHub issue

There are several places indicating that the argument sort can be used universally to set a custom ordering by passing an array (list) with the desired order. This works for categories on the x-axis of a grouped bar chart but not the y-axis.

Current versions:

# Name                    Version                   Build  Channel
altair                    4.0.1                      py_0    conda-forge
jupyterlab                1.2.6                      py_0    conda-forge

Example (vega-lite spec):

import pandas as pd
import altair as alt

resource_order = [
    "Onshore Wind",
    "Solar",
    "Battery",
    "NGCC",
]
resource_color_scale = alt.Scale(
    domain=resource_order, 
    range=[
        "#17becf", # onshore wind
        "#d62728",  # solar 
        '#c5b0d5', # battery
        "#bcbd22", # NGCC
    ]
)
resource_colors = alt.Color("Resource Name", scale=resource_color_scale)
    
data = pd.DataFrame(
    {
        "Resource Name": ["Battery", "NGCC", "Onshore Wind", "Solar"] * 2, 
         "Capacity": [2, 20, 10, 15, 3, 10, 30, 25], 
         "Case": ["A", "A", "A", "A", "B", "B", "B", "B"]
    }
)

alt.Chart(data).mark_bar().encode(
    x=alt.X('Case', sort=["B", "A"]), # Default order is alphabetical "A", "B"
    y=alt.Y('Capacity', sort=resource_order),
    color=resource_colors
)

image

I did, however, find a workaround by ordering according to a new indexing column (vega-lite spec):

resource_order_idx = {
    resource: idx 
    for idx, resource in enumerate(resource_order[::-1]) # Reverse list to align colors
}                                                        # with legend order

# Create "idx" column with integer values indicating order in stacked bar
data["idx"] = data["Resource Name"].map(resource_order_idx)

alt.Chart(data).mark_bar().encode(
    x=alt.X('Case', sort=["B", "A"]),
    y=alt.Y('Capacity'),
    order="idx",
    color=resource_colors
)

image

I’m not sure if this is a bug in vega-lite, an oversight in the API, or the way that it is supposed to work, but I’m providing this example and my work-around to help anyone else who might be searching for for help with the same issue.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:2
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
jakevdpcommented, Feb 25, 2020

I believe this issue tracks the functionality you want.

1reaction
jakevdpcommented, Feb 25, 2020

The order encoding is the documented way to specify sort order for stacked bars, so I believe this is working as intended.

The docs on the Altair side, as always, could be improved.

Read more comments on GitHub >

github_iconTop Results From Across the Web

pandas - Sorting a stacked bar chart
However, the sort parameter of alt.Order only accepts 'ascending' or 'descending'. I would like to customize the order to be Green, Yellow, Red, ......
Read more >
How to Sort Segments Within Stacked Bars by Value in Tableau
Drag Category to Columns. 3.Drag Sales to Rows. 4.Drag Region to Color. 5.Drag Sales to Label. Step 2: Sort the Bar Segments 1....
Read more >
SORT STACKED BAR- TABLEAU - YouTube
Your browser can 't play this video. Learn more. Switch camera.
Read more >
Sorting a Legend Independently from the Order of Fields in a ...
Right-click [Category] on the Rows shelf and select Sort… ... Right-click the "Stacked Bar Chart - just color legend" worksheet on the dashboard...
Read more >
Tableau Tips: Sorting Stacked Bars - Data Vizzes
Before we go to sorting of the stacked bars, lets first try to build it. To do that follows these steps: 1- Drag...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found