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',
)
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With