How to conveniently plots 4 character integers as years (temporal data) #3140
-
This is an Altair user question xD What is a good way of visualizing years stored as integers? If I naively plot them "as is", the formatting with the thousands separator "," will be unfortunate and I have to add import altair as alt
from vega_datasets import data
source = data.wheat()
alt.Chart(source).mark_point().encode(
x=alt.X("year:Q").scale(zero=False), # could fix the formatting with `.axis(format='i')` but that + scale is a lot of typing
y='wheat',
) Another way would be to treat the years as ordinal, but that creates a wide chart with a redundant amount of axis labels: alt.Chart(source, width=600).mark_point().encode(
x=alt.X("year:O"),
y='wheat',
) I could convert them in pandas, but that is syntactically cumbersome and also stores them incorrectly in the pandas dataframe as import pandas as pd
# `to_datetime doesn't work for older dates, but I think `parse_dates` in `read_csv` would
alt.Chart(source.assign(year=pd.to_datetime(source['year'], format='%Y', errors='coerce'))).mark_point().encode(
x="year",
y='wheat',
) I wish I could just append alt.Chart(source).mark_point().encode(
x="year:T",
y='wheat',
) And the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Yeah that would be nice. The shortest I can come up with is converting it to a datetime and back with Vega expressions: alt.Chart(source).mark_point().transform_calculate(
x_date="datetime(datum.year, 0)"
).encode(
x="year(x_date):T",
y="wheat",
) |
Beta Was this translation helpful? Give feedback.
Use
str
asdtype
for theyear
column in your dataframe works as well:Not sure how you could know this upfront.