Graphically split time history

Viewed 41

I'm trying to make a simple function allowing a user to split a time history into two parts. The user should be able to click and the x-axis value should be returned so that the output is divided into two DataFrames.

import pandas as pd
import numpy as np

df = pd.DataFrame({"data": np.random.rand(100)})

def split_TH(df):
    df.plot()
    #User clicks where the split should be: callback from graph is time `t`
    return df.iloc[:t], df.iloc[t:]

I've looked into plotly and dash, as well as anything I can find in matplotlib, but nothing I can see can make callbacks to the code that generated the graph, only callbacks within the plot itself. I'm sure there's some simple way to do this but I can't find it.

1 Answers

I think I have found an answer, but would love if anyone who is more expert can improve:

df = pd.DataFrame({"data": np.random.rand(100)})

def split_TH(df):
    fig, ax = plt.subplots()
    df.plot(ax = ax)
    def onclick(event):
        global t
        t = event.xdata
        
    cid = fig.canvas.mpl_connect('button_press_event', onclick)
    plt.waitforbuttonpress()
    return df[:int(t)], df[int(t):]

df1, df2 = split_TH(df)
Related