Benj Cabalona Jr.
Benj Cabalona Jr.

Reputation: 439

Line Chart with Custom Confidence Interval in Altair

Suppose i have the data frame below:

Selection_101

I checked the documentation but it's only based on a single column.

Reproducible code:

x = np.random.normal(100,5,100)
data = pd.DataFrame(x)
epsilon = 10
data.columns = ['x']
data['lower'] = x - epsilon
data['upper'] = x + epsilon
data

I'd actually like to use altair, since i like it's interactivity.

Upvotes: 8

Views: 2381

Answers (2)

joelostblom
joelostblom

Reputation: 48889

Just adding that you can also use mark_errorband instead of mark_area for the same result:

alt.Chart(data).mark_errorband(
    opacity=0.5
).encode(
    x='index',
    y='lower',
    y2='upper'
)

enter image description here

And if the dataframe looks slightly different and contains the upper and lower bound relative the center value instead of in absolute value, you can instead use mark_errorband with the yError and yError2 encodings as per the second example in this section of the docs:

data = pd.DataFrame({
    'x': x,
    'lower': - epsilon,
    'upper': + epsilon
}).reset_index()

alt.Chart(data).mark_errorband(
    opacity=0.5
).encode(
    x='index',
    y='x',
    yError='lower',
    yError2='upper'
)

enter image description here

Upvotes: 0

jakevdp
jakevdp

Reputation: 86320

You can layer a line and an area chart, usng the y and y2 encodings to specify the range:

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

x = np.random.normal(100,5,100)
epsilon = 10
data = pd.DataFrame({
    'x': x,
    'lower': x - epsilon,
    'upper': x + epsilon
}).reset_index()

line = alt.Chart(data).mark_line().encode(
    x='index',
    y='x'
)

band = alt.Chart(data).mark_area(
    opacity=0.5
).encode(
    x='index',
    y='lower',
    y2='upper'
)

band + line

enter image description here

Upvotes: 15

Related Questions