Last active
January 29, 2022 14:40
-
-
Save mneedham/e5d347cbffe0b04584a267c0d961e1a1 to your computer and use it in GitHub Desktop.
Altair - Setting a custom date domain for the x axis
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
# 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