plotnine icon indicating copy to clipboard operation
plotnine copied to clipboard

Using `geom.abline` with date-time x-axis

Open wcass77 opened this issue 4 years ago • 1 comments

I am trying to create a custom line over time of my time series data. I am using the numpy datetime objects from a pandas dataframe for the x-axis. That is working fine overall. However, I can't figure out how to specify the slope in this case. It is not clear what the underlying units on the axis are, so dividing by a time delta to get a rate doesn't work.

Here is a minimal example of a working time series plot:

import pandas as pd
import numpy as np
import plotnine as p9


def make_date(date_str):
    return pd.Timestamp(date_str).to_numpy()

# Plot some random time series data
df = pd.DataFrame(
    {
        "date_time": [make_date(d) for d in ["2000-1-1", "2000-2-1", "2000-3-1", "2000-4-15", "2000-6-1"]],
        "value": [10, 15, 20, 23, 35],
    }
)
gg = (
    p9.ggplot(df, p9.aes(x="date_time", y="value"))
    + p9.geom_point()
    + p9.scale_x_date(date_labels="%Y %b %d")
)
gg

The above code works great. As an example, say I want to make a line that goes through the first and last points:

# Create a line going through the first and last points
delta_t = df["date_time"].iloc[-1] - df["date_time"].iloc[0]
delta_value = df["value"].iloc[-1] - df["value"].iloc[0]
slope = delta_value / delta_value # doesn't work - dividing by timedelta not well definied
intercept = df["value"].iloc[0] - slope * df["date_time"].iloc[0]

gg + p9.geom_abline(slope=slope, intercept=intercept)

The above code doesn't work. I tried looking for examples online and digging through the documentation and code, but couldn't figure out how to do it. Is this a limitation of plotnine or am I missing something?

Also, you can run the code above in a notebook here, if that's helpful: https://colab.research.google.com/drive/1L_ANCkMQuB5EaWRSpdO3MqL3etEJWhcH?usp=sharing

Thank you for your help!

wcass77 avatar Dec 09 '21 19:12 wcass77

This is late, but in case someone has a similar issue. With geom_abline it may not be easy to compute the slope if you can not do arithmetic with the x and y aesthetics. It is better to use geom_segment.

import pandas as pd
import numpy as np
from plotnine import *

def make_date(date_str):
    return pd.Timestamp(date_str).to_numpy()

# Plot some random time series data
df = pd.DataFrame(
    {
        "date_time": [make_date(d) for d in ["2000-1-1", "2000-2-1", "2000-3-1", "2000-4-15", "2000-6-1"]],
        "value": [10, 15, 20, 23, 35],
    }
)

df2 = pd.DataFrame({
    'x': [df['date_time'].iloc[0]],
    'xend': df['date_time'].iloc[-1],
    'y': df['value'].iloc[0],
    'yend': df['value'].iloc[-1]
})

(
    ggplot(df, aes(x="date_time", y="value"))
    + geom_point()
    + geom_segment(df2, aes('x', 'y', xend='xend', yend='yend'))
    + scale_x_date(date_labels="%Y %b %d")
)

line

has2k1 avatar Mar 31 '22 09:03 has2k1