Xavier Olive research teaching python blog til cli

Color schemes in Vega/Vega-Lite/Altair

27 September 2021

Some default color palettes are definitely nice looking and it is nice to be able to see the color codes together with a color sample. It is nice to be able to do that in Altair.

I don’t know whether it is possible to get the definition of the colors in Altair, but they are coded in the Vega source code here

import altair as alt

tableau20 = (
  "4c78a89ecae9f58518ffbf7954a24b88d27ab79a20f2cf5b43989483bcb6"
  "e45756ff9d9879706ebab0acd67195fcbfd2b279a2d6a5c99e765fd8b5a5"
)

colors = (
    pd.DataFrame(
        list(
            "#" + tableau20[6 * i : 6 * i + 6]
            for i in range(len(tableau20) // 6)
        )
    )
    .rename(columns={0: "color"})
    .assign(x=1)
)
(
    alt.Chart(colors)
    .mark_bar(height=20)
    .encode(
        alt.Y(
            "color",
            scale=alt.Scale(
                domain=colors.color.values,
                scheme="tableau20",
            ),
            title=None,
        ),
        alt.Color(
            "color",
            scale=alt.Scale(
                domain=colors.color.values,
                scheme="tableau20",
            ),
            legend=None,
        ),
    )
    .properties(width=200, height=500, title="tableau20")
    .configure_title(
        font="Fira Sans",
        fontSize=20,
        anchor="start",
        dy=-10,
    )
    .configure_axis(
        labelFont="Inconsolata",
        labelFontSize=16,
        labelPadding=10,
    )
    .configure_view(stroke=None)
)