How to specify the color for each data series?

In this example:

import altair as alt
from vega_datasets import data
import pandas as pd

stocks = data.stocks()
source = stocks.groupby([pd.Grouper(key="date", freq="6M"),"symbol"]).mean().reset_index()

alt.Chart(source).mark_line(point = True).encode(
    x=alt.X("date:O", timeUnit="yearmonth", title="date"),
    y="rank:O",
    color=alt.Color("symbol:N")
).transform_window(
    rank="rank()",
    sort=[alt.SortField("price", order="descending")],
    groupby=["date"]
).properties(
    title="Bump Chart for Stock Prices",
    width=600,
    height=150
)

rendered chart with default colors

I want to apply custom color to each symbol, such as

  • AAPL - Gray
  • AMZN - Light Gray
  • GOOG - White
  • IBM - Purple
  • MSFT - Yellow.

Is that possible? How to do it?


Solution 1:

Create the user's own palette and set it to the scale of the color channel. I change the white to pink because I am not sure if white is rendering.

import altair as alt
from vega_datasets import data
import pandas as pd

stocks = data.stocks()
source = stocks.groupby([pd.Grouper(key="date", freq="6M"),"symbol"]).mean().reset_index()

palette = alt.Scale(domain=['AAPL', 'AMZN', 'GOOG', 'IBM', 'MSFT'],
                  range=['gray', 'lightgray', 'pink', 'purple', 'yellow'])

alt.Chart(source).mark_line(point = True).encode(
    x = alt.X("date:O", timeUnit="yearmonth", title="date"),
    y="rank:O",
    color=alt.Color("symbol:N", scale=palette)
).transform_window(
    rank="rank()",
    sort=[alt.SortField("price", order="descending")],
    groupby=["date"]
).properties(
    title="Bump Chart for Stock Prices",
    width=600,
    height=150,
)

enter image description here

Solution 2:

This should do the trick. Not sure though if it is the most efficient way

import altair as alt
from vega_datasets import data
import pandas as pd

stocks = data.stocks()
source = stocks.groupby([pd.Grouper(key="date", freq="6M"),"symbol"]).mean().reset_index()
colormap = {"AAPL":"Gray", "AMZN":"LightGRAY", "GOOG":"White", "IBM":"purple", "MSFT":"Yellow"}
chart = alt.Chart(source).mark_line(point = True).encode(
x = alt.X("date:O", timeUnit="yearmonth", title="date"),
y="rank:O",
color=alt.Color('symbol', scale=alt.Scale(
        domain=list(colormap.keys()),
        range=list(colormap.values())))
).transform_window(
 rank="rank()",
 sort=[alt.SortField("price", order="descending")],
 groupby=["date"]
).properties(
 title="Bump Chart for Stock Prices",
 width=600,
 height=150,
)