1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| from matplotlib import pyplot as plt
import numpy as np
import datetime as dt
import pandas as pd
class LineBuilder(object):
def __init__(self, fig, ax):
self.xs = []
self.ys = []
self.ax = ax
self.fig = fig
def mouse_click(self, event):
print('click', event)
if not event.inaxes:
return
#left click
if event.button == 1:
self.xs.append(event.xdata)
self.ys.append(event.ydata)
#add a line to plot if it has 2 points
if len(self.xs) % 2 == 0:
line, = self.ax.plot([self.xs[-2], self.xs[-1]], [self.ys[-2], self.ys[-1]], 'g')
line.figure.canvas.draw()
#right click
if event.button == 3:
if len(self.xs) > 0:
self.xs.pop()
self.ys.pop()
#delete last line drawn if the line is missing a point,
#never delete the original stock plot
if len(self.xs) % 2 == 1 and len(self.ax.lines) > 1:
self.ax.lines.pop()
#refresh plot
self.fig.canvas.draw()
def mouse_move(self, event):
if not event.inaxes:
return
if len(self.xs) % 2 == 1:
line, =self.ax.plot([self.xs[-1], event.xdata], [self.ys[-1], event.ydata], 'r')
line.figure.canvas.draw()
self.ax.lines.pop()
start = dt.datetime(2014, 1, 1)
end = dt.datetime(2019, 10, 30)
df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
columns=['a', 'b', 'c'])
x = df2['a']
y = df2['b']
x_num_index = np.arange(0, len(x), 1)
fig, ax = plt.subplots()
draw_line = LineBuilder(fig, ax)
fig.canvas.mpl_connect('button_press_event', draw_line.mouse_click)
fig.canvas.mpl_connect('motion_notify_event', draw_line.mouse_move)
ax.scatter(df2.a, df2.b,c='red')
plt.gcf().autofmt_xdate()
plt.show() |