Search code examples
altair

Trying to set Altair color to white at zero value


I'm trying to create an Altair heat map where the color is white when my count is zero.

Here is my data frame:

df11 = pd.DataFrame({
    'lineid': [0,1,2,0,1,2],
    'term': ['data', 'data', 'data', 'explore', 'explore', 'explore'],
    'count': [3,2,1,1,0,2],
    'title': ['weather', 'weather','weather','weather','weather','weather',]
})
alt.Chart(d11).mark_rect().encode(
    x=alt.X('lineid:O', title=None, axis=alt.Axis(ticks=False, labels=False)),
    y=alt.Y('term:O', title=None),
    color=alt.Color('count:O', legend=None)
)

The encoding gives me this chart (which is what I intended) but I'm trying to get the zero count (2nd row, 2nd column) to be white not light blue.

enter image description here


Solution

  • You can use a conditional encoding as in How to make Altair display NaN points with a quantitative color scale?

    import altair as alt
    import pandas as pd
    
    df = pd.DataFrame({
        'lineid': [0,1,2,0,1,2],
        'term': ['data', 'data', 'data', 'explore', 'explore', 'explore'],
        'count': [3,2,1,1,0,2],
        'title': ['weather', 'weather','weather','weather','weather','weather',]
    })
    alt.Chart(df).mark_rect().encode(
        x=alt.X('lineid:O', title=None, axis=alt.Axis(ticks=False, labels=False)),
        y=alt.Y('term:O', title=None),
        color=alt.condition(alt.datum.count == 0, alt.value('white'), 'count:O', legend=None)
    )
    

    enter image description here