Can mark_rule be extended outside the chart with Altair?

Viewed 144

Is there a way to make a rule mark longer without disrupting the axes of a chart? If I have this:

random.seed(0)
df = pd.DataFrame({'x':[i for i in range(1,21)],'y':random.sample(range(1,50), 20)})
chart = alt.Chart(df).mark_area().encode(x='x',y='y')
ruler = alt.Chart(pd.DataFrame({'x':[5]})).mark_rule().encode(x='x')
chart+ruler

enter image description here

But I want this

: enter image description here

2 Answers

Have you tried to overlay an empty plot on top with wider margins? So the overlay plot just includes the line, but since it has larger margins on the bottom it will extend past the original plot.

You can set an explicit y-domain and then set clip=False inside mark_rule, but you also need to define the y-range of the rule since the default is to stretch over the entire plot:

import altair as alt
import pandas as pd
import random


random.seed(0)
df = pd.DataFrame({'x':[i for i in range(1,21)],'y':random.sample(range(1,50), 20)})
chart = alt.Chart(df).mark_area().encode(x='x', y=alt.Y('y', scale=alt.Scale(domain=(0, 50))))
ruler = alt.Chart(pd.DataFrame({'x':[5], 'y': [-10], 'y2': [50]})).mark_rule(clip=False, fill='black').encode(x='x', y='y', y2='y2')
chart+ruler

enter image description here

Related