plotbar-chartaltaircolor-scheme

Set color scheme for each chart in column layout individually


Consider the following example of a bar plot in horizontal layout. In each chart the y and color channels both encode column "y" of df.

import altair as alt
import numpy as np
import polars as pl

N = 20
df = pl.DataFrame({
    'x': np.repeat(range(N), 2),
    'y': np.random.randint(0, 100, 2*N),
    'class': np.tile(["A", "B"], N)
})
alt.Chart(df).mark_bar().encode(
    x='x',
    y='y',
    column='class',
    color=alt.Color('y', scale=alt.Scale(scheme='greens'))
)

How do I set the color scheme individually for each chart? Spltting the whole thing in two seperate charts does not work:

a1 = (alt.Chart(df.filter(pl.col('class')=="A"))
    .mark_bar()
    .encode(x='x', y='y', color=alt.Color('y', scale=alt.Scale(scheme="greens"))))

a2 = (alt.Chart(df.filter(pl.col('class')=="B"))
    .mark_bar()
    .encode(x='x', y='y', color=alt.Color('y', scale=alt.Scale(scheme="oranges"))))

a1 | a2

The scale in a2 is ignored.


Solution

  • You can tell altair to resolve the color scales seperately:

    a1 = (alt.Chart(df.filter(pl.col('class')=="A"))
        .mark_bar()
        .encode(x='x', y='y', color=alt.Color('y', scale=alt.Scale(scheme="greens"))))
    
    a2 = (alt.Chart(df.filter(pl.col('class')=="B"))
        .mark_bar()
        .encode(x='x', y='y', color=alt.Color('y', scale=alt.Scale(scheme="oranges"))))
    
    (a1 | a2).resolve_scale(color="independent")
    

    image of independent scale

    More info in the docs.