essicolo
essicolo

Reputation: 818

Stack area chart with quantitative x-axis with altair

Area charts in altair are automatically stacked when the x-axis is time. But when x belongs to a quantitative data type, areas are not stacked.

import pandas as pd
import numpy as np
import string
import altair as alt

np.random.seed(394378)
n_series = 3
series_names = list(string.ascii_lowercase)[:n_series]
x_range = range(0, 21)
df = pd.DataFrame({"Series": np.tile(series_names, len(x_range)),
                   "X": np.repeat(x_range, n_series),
                   "Y": np.random.poisson(lam = 10, size = len(x_range) * n_series)})

alt.Chart(df).\
    mark_area().\
    encode(
        x = "X:Q",
        y = "Y:Q",
        color = "Series:N"
)

(stack area chart (not)

How can I stack areas?

Upvotes: 1

Views: 123

Answers (1)

jakevdp
jakevdp

Reputation: 86330

You can do this by passing stack=True to the y encoding. For example:

alt.Chart(df).\
    mark_area().\
    encode(
        x = "X:Q",
        y = alt.Y("Y:Q", stack=True),
        color = "Series:N"
)

enter image description here

Upvotes: 1

Related Questions