Created
May 6, 2022 20:33
-
-
Save aaronj1335/1f3dbee7e695bfe26b8e786415983b4e to your computer and use it in GitHub Desktop.
code to plot some time series data with a vertical rule and hover box with the data point values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data['Date'] = data['Date'].map(lambda d: f'{d}') | |
data = data.melt('Date') | |
# display(data) | |
line = altair.Chart(data).mark_line().encode( | |
x=altair.X('Date:T', axis=altair.Axis(labelAngle=50, labelSeparation=10, | |
format='%Y-%m-%d')), | |
y=altair.Y('value', title=None, axis=altair.Axis(format='$,f')), | |
color='variable', | |
) | |
# Create a selection that chooses the nearest point & selects based on | |
# x-value | |
nearest = altair.selection(type='single', nearest=True, on='mouseover', | |
fields=['Date'], empty='none') | |
# Transparent selectors across the chart. This is what tells us | |
# the x-value of the cursor | |
selectors = altair.Chart(data).mark_point().encode( | |
x='Date:T', | |
opacity=altair.value(0), | |
).add_selection( | |
nearest | |
) | |
# Draw points on the line, and highlight based on selection | |
points = line.mark_point().encode( | |
opacity=altair.condition(nearest, altair.value(1), altair.value(0)) | |
) | |
# Draw text labels near the points, and highlight based on selection | |
text = line.mark_text(align='right', dx=-5, dy=-10).encode( | |
text=altair.condition( | |
nearest, 'value', altair.value(' '), format='$,d') | |
) | |
# Draw a rule at the location of the selection | |
rules = altair.Chart(data).mark_rule(color='gray').encode( | |
x='Date', | |
).transform_filter( | |
nearest | |
) | |
# Put the five layers into a chart and bind the data | |
return altair.layer( | |
line, selectors, points, rules, text | |
).properties( | |
width=1000, height=300 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment