Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Altair: Create a mark_line chart with a max-min band similar to mark_errorband

Tags:

python

altair

I've been working to create a chart similar to this EIA Chart (data at linked page): enter image description here

I've seen a similar example using Altair in the line chart with confidence interval band gallery example but I do not see a way to explicitly set the "extent" with my own values using the mark_errorband method. The documentation provides that you can use one of 4 methods to set the extent but I can't figure out how to pass in my own values. The mark_errorband examples make me believe that this must be possible however I am at a loss as to how to accomplish it.

I'd appreciate any guidance on how an min-max band may be achieved in Altair.

like image 733
XonAether Avatar asked Jul 23 '20 15:07

XonAether


People also ask

What is Altair chart?

Altair is a declarative statistical visualization library for Python, based on Vega and Vega-Lite. Altair offers a powerful and concise visualization grammar that enables you to build a wide range of statistical visualizations quickly.

How do I change my Altair scale?

By default Altair uses a linear mapping between the domain values (MIC) and the range values (pixels). To get a better overview of the data, we can apply a different scale transformation. To change the scale type, we'll set the scale attribute, using the alt. Scale method and type parameter.

How do I save my Altair chart?

Additionally, you can save a chart to a JSON file using Chart. save() , by passing a filename with a . json extension.


1 Answers

You can use an area mark with the y and y2 encodings. For example:

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

x = np.linspace(0, 10)
y = np.sin(x) + 0.1 * np.random.randn(len(x))

df = pd.DataFrame({
    'x': x,
    'y': y,
    'upper': y + 0.5 * (1 + np.random.rand(len(x))),
    'lower': y - 0.5 * (1 + np.random.rand(len(x)))
})

line = alt.Chart(df).mark_line(
    color='black'
).encode(
    x='x',
    y='y'
)

band = alt.Chart(df).mark_area(
    opacity=0.5, color='gray'
).encode(
    x='x',
    y='lower',
    y2='upper'
)

band + line

enter image description here

Under the hood, mark_errorband is essentially a macro within Vega-Lite that computes lower/upper bounds and automatically populates the y and y2 encodings for you.

like image 198
jakevdp Avatar answered Sep 27 '22 15:09

jakevdp