Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shade a region with Altair

This is how I would like the image to look like

I am trying to shade different regions in my plot created with Altair (like axvspan in matplotlib) but can't find a way to do it.

Chart(data).mark_line(color='r').encode(
    x=X('Voltage'),
    y=Y('Current (pA)', axis=Axis(format='r'), title='Current (pA)'),
    color='Line polarity:N',
    shape='Line polarity:N',
)
like image 973
Yiti Avatar asked Apr 18 '17 20:04

Yiti


People also ask

Is Altair interactive?

Altair's interactivity and grammar of selections are one of its unique features among available plotting libraries. In this section, we will walk through the variety of selection types that are available, and begin to practice creating interactive charts and dashboards.


1 Answers

The best way to mimic matplotlib's axvspan in Altair is with a rect mark tied to pixel values in the y-axis.

Here is an example:

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

np.random.seed(1701)

data = pd.DataFrame({
    'Voltage': np.linspace(0, 100, 10),
    'Current': np.random.randn(10).cumsum()
})

cutoff = pd.DataFrame({
    'start': [0, 8, 30],
    'stop': [8, 30, 100]
})

line = alt.Chart(data).mark_line().encode(
    x=alt.X('Voltage'),
    y=alt.Y('Current')
)

areas = alt.Chart(
    cutoff.reset_index()
).mark_rect(
    opacity=0.2
).encode(
    x='start',
    x2='stop',
    y=alt.value(0),  # pixels from top
    y2=alt.value(300),  # pixels from top
    color='index:N'
)

(areas + line).interactive()

enter image description here

like image 186
jakevdp Avatar answered Oct 07 '22 11:10

jakevdp