lorenae
lorenae

Reputation: 43

Altair python: solid horizontal bars in the backgound

I'd like to do something like this in altair

what I want

What I have accomplished so far is the following, and I can't figure out how to paint the background as I need

what I have

import pandas as pd
from vega_datasets import data

source = data.cars()

line = alt.Chart(source).mark_line().encode(
    x='Year',
    y='mean(Miles_per_Gallon)'
)

band0 = alt.Chart(pd.DataFrame({'y': [20]})).mark_rule(color='red').encode(y='y')
band1 = alt.Chart(pd.DataFrame({'y': [30]})).mark_rule(color='orange').encode(y='y')

line + band0 + band1

Thanks in advance! Lorena

Upvotes: 2

Views: 586

Answers (1)

joelostblom
joelostblom

Reputation: 49054

You can do this via mark_rect and a y2 encoding as per this gallery example and How to shade a region with Altair.

import pandas as pd
from vega_datasets import data
import altair as alt

source = data.cars()
line = alt.Chart(source).mark_line().encode(
    x='Year',
    y='mean(Miles_per_Gallon)')

band0 = (alt.Chart(pd.DataFrame({'y': [0], 'y2':[30]}))
         .mark_rect(color='red', opacity=0.3)
         .encode(y='y', y2='y2'))
band1 = (alt.Chart(pd.DataFrame({'y': [20], 'y2':[35]}))
         .mark_rect(color='yellow', opacity=0.3)
         .encode(y='y', y2='y2'))

line + band0 + band1

enter image description here

Upvotes: 3

Related Questions