Skip to content

Instantly share code, notes, and snippets.

@mneedham
Last active Jan 14, 2020
Embed
What would you like to do?
Altair - Setting a custom date domain for the x axis
# Code for https://markhneedham.com/blog/2020/01/14/altair-range-values-dates-axis/ blog post
import altair as alt
import pandas as pd
import datetime
df = pd.DataFrame( [
{"position": 40, "date": datetime.date(2019,9,5)},
{"position": 31, "date": datetime.date(2019,9,12)},
{"position": 19, "date": datetime.date(2019,9,19)},
{"position": 14, "date": datetime.date(2019,9,26)},
{"position": 7, "date": datetime.date(2019,10,3)},
{"position": 1, "date": datetime.date(2019,10,10)},
{"position": 1, "date": datetime.date(2019,10,17)},
{"position": 1, "date": datetime.date(2019,10,24)},
])
df["date"] = pd.to_datetime(df["date"])
chart = alt.Chart(df).mark_point(color="red").encode(
x='date',
y='position')
chart.save("chart.html")
# domain is Pandas index
domain_pd = pd.to_datetime(['2019-01-01', '2019-12-31']).astype(int) / 10 ** 6
chart = alt.Chart(df).mark_point(color="red").encode(
x=alt.X('date:T', timeUnit='yearmonthdate', scale=alt.Scale(domain=list(domain_pd))),
y='position')
chart.save("chart.html")
# domain is start and end dates
domain = ["2019-01-01", "2019-12-31"]
chart = alt.Chart(df).mark_point(color="red").encode(
x=alt.X('date:T', timeUnit='yearmonthdate', scale=alt.Scale(domain=domain)),
y='position')
chart.save("chart.html")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment