Search code examples
pythonaltairvega-lite

Setting Colors in Altair Layered Chart


Similar to Setting colors in Altair charts I am using a layered chart and I like to set excplicit colors. Somehow, when I use the solution from the answer, my colors are always changing to some arbitrary colors. I wonder, if anyone knows, why this happens and how to force altair to use the colors given in the colors array.

Here a test example:

import altair as alt
from vega_datasets import data

source = data.movies()
colors = ['#170c3b', '#fa8d0b']


plot = alt.Chart(source).mark_line().encode(
    x=alt.X("IMDB_Rating", bin=True),
    y=alt.Y(
        alt.repeat("layer"), aggregate="mean", title="Mean of US and Worldwide Gross"
    ),
    color=alt.datum(alt.repeat("layer")),
).repeat(
    layer=["US_Gross", "Worldwide_Gross"]
).configure_range(
        category=alt.RangeScheme(scheme=colors)
)

plot.show()

Here the colors from the array:

#170c3b #fa8d0b
enter image description here enter image description here

Here the plot with changed colors: enter image description here


Solution

  • The category=alt.RangeScheme(scheme=colors) should be category=alt.RangeScheme(colors) instead.

    import altair as alt
    from vega_datasets import data
    
    source = data.movies()
    colors = ['#170c3b', '#fa8d0b']
    
    
    plot = alt.Chart(source).mark_line().encode(
        x=alt.X("IMDB_Rating", bin=True),
        y=alt.Y(
            alt.repeat("layer"), aggregate="mean", title="Mean of US and Worldwide Gross"
        ),
        color=alt.datum(alt.repeat("layer")),
    ).repeat(
        layer=["US_Gross", "Worldwide_Gross"]
    ).configure_range(
            category=alt.RangeScheme(colors)
    )
    
    plot
    

    yields:
    plot