Altair LOESS Smoothing with Date

Viewed 61

i liked making Plots with Altair lately, unfortunately Smoothing of Timeseries doesn't work that well.

So this is my base plot (the data doesn't really need smoothing, but let's ignore that)

import altair as alt
from vega_datasets import data

temps = temps[temps.date < '2010-01-15']

alt.Chart(temps).mark_line().encode(
    x='date:T',
    y='temp:Q'
)

If i just use transform_loess on it, i get an empty plot:

alt.Chart(temps).mark_line().encode(
    x='date:T',
    y='temp:Q'
).transform_loess("date","temp",bandwidth=.3)

If i transform the Datetime Variable to Ordinal it works, but the x-axis is not correct anymore, i already tried some formatting, but with no success:


from datetime import datetime

temps['date_ordinal'] = temps['date'].apply(lambda date: datetime.timestamp(date))

alt.Chart(temps).mark_line().encode(
    x = alt.X('date_ordinal:T', axis = alt.Axis( format = ("%Y%b%d%H"))),
    y='temp:Q'
).transform_loess("date_ordinal","temp",bandwidth=.05)

I'm aware i could also just smooth the data beforehand, but my original dataset has many variables, so i would need to do it in a pandas groupby somehow.

Thanks for your help!

1 Answers

I was looking to do something similar. This isn't much better than doing it outside of altair, but it will work ¯_(ツ)_/¯:

import altair as alt
from vega_datasets import data

alt.data_transformers.disable_max_rows()
temps = data.seattle_temps()
temps["t"] = temps["date"].apply(
    lambda d: d.timestamp()
)

a = alt.Chart(temps).mark_line().encode(
    x='date',
    y='temp:Q'
)
b = alt.Chart(temps).mark_line().encode(
    x=alt.X('t', title=None, axis=alt.Axis(labels=False, ticks=False),
            scale=alt.Scale(nice=False)),
    y='temp:Q',
)

a + b.transform_loess('t', 'temp').mark_line(size=4, color="red")

Plot

Related