When I plot time on the x axis with altair it doesn't show year. Is it possible to fix this?

Viewed 1075

I really enjoy using altair. However, sometimes when I plot time, it doesn't show the year and just months. I tried changing the dimensions and still can't get it unless the width is so large it makes the image less user friendly.

import altair as alt
df_all['Date'] = pd.to_datetime(df_all['Date'])

alt.Chart(df_all).mark_line().encode(
    x='Date:T',
    y='Values',
    color='Key',
).properties(height=500, width=600)

The data has these types:

Date      datetime64[ns]
Key               object
Values           float64

And looks like this:

Date,Key,Values
2020-01-12,Leisure - Family,100.000000
2020-01-12,Leisure - Non-Family,100.000000
2020-01-12,Business,100.000000
2020-01-19,Leisure - Family,101.989826
2020-01-19,Business,95.664472

Output looks like this:

https://imgur.com/a/D9AlvLj

Thanks a lot in advance!

1 Answers

You can change the axis format to any D3 time format, for example:

import pandas as pd
import altair as alt


df = pd.read_clipboard(sep=',', parse_dates=['Date'])

alt.Chart(df).mark_line().encode(
    x=alt.X('Date', axis=alt.Axis(format='%e %b, %Y')),
    y=alt.Y('Values', scale=alt.Scale(zero=False)),
    color='Key') 

enter image description here

Related