Highlighting specific columns in bar chart in python using altair

Viewed 294

I want to highlight specific data points in a bar chart in python based on my requirement. using altair, I am able to achieve results for one data point (for e.g 'A' in the code). Here's the sample data frame and code

import pandas as pd
import altair as alt

df = pd.DataFrame({
    'Rank': [25, 20, 40, 10, 50, 35],
    'Name': ['A', 'B', 'C', 'D', 'E', 'F'],   
})


bar1 =alt.Chart(df).mark_bar().encode( y = alt.Y('Rank'),
                                       x = alt.X('Name:O', sort ='x'),
    color=alt.condition(
        alt.datum.Name == 'A',  
        alt.value('red'),     
        alt.value('blue')     
    ))
bar1

enter image description here

How can I highlight two or more datapoints (eg. A & B) with the same color and others with a different one? I tried passing the names as a list Select = ['A', 'B'] and then passing the alt.datum.Name == Select but that does not work?

How can i get this done? Also, trying to understand why passing as a list did not work? thank you

1 Answers

You could use the FieldOneOfPredicate to check if the Name column is one of the items in the list:

import pandas as pd
import altair as alt

df = pd.DataFrame({
    'Rank': [25, 20, 40, 10, 50, 35],
    'Name': ['A', 'B', 'C', 'D', 'E', 'F'],   
})


bar1 =alt.Chart(df).mark_bar().encode( y = alt.Y('Rank'),
                                       x = alt.X('Name:O', sort ='x'),
    color=alt.condition(
        alt.FieldOneOfPredicate('Name', ['A', 'B']),
        alt.value('red'),     
        alt.value('blue')     
    ))
bar1

enter image description here

You can read more about it in the VegaLite docs. You could also use two expression string with an "or" operator:

color=alt.condition(
    "datum.Name == 'A'"
    "|| datum.Name == 'B'",  # splitting on two rows for readability
    alt.value('red'),     
    alt.value('blue')     
)

I don't think there is a single Vega expression operator that you can use for checking membership like Python's in. This answer doesn't mention it either.

Related