上一篇文章粗略介绍了一下matplotlib的基本概念,见matplotlib 初步介绍
之所以写这篇,是记录一下自己对matplotlib中的event的event交互的学习及使用
下面就event交互来介绍我的真实使用情况
这里面的交互用到了两个,pick_event
和key_press_event
,实现的功能是想要在线上面可以标注并设定区域,下面是标注类的代码和注释
class MarkState(object):
def __init__(self):
self.start = 0 # 区域的起始点
self.end = 0 # 区域的结束点
self.state = 0 # 区域的状态
self.states = ['1', '2', '3'] # 接受的状态
self.picked = [] # 当前选择的点
self.vspans = [] # 垂直区域
self.vlines = [] # 垂直线
self.linedict = {} # 对应x轴坐标到vlines中的对应的index
self.steps = [] # 各个步骤(用于撤销操作)
def _reset(self): # 重置参数(重新画图)
self.linedict.clear()
self.vspans = []
self.vlines = []
self.picked = []
self.steps = []
def PointPick(self, event): # 画垂直线
ind = event.ind # 这里注意一点,当途中点击的点比较密集时,可能一次点击会选中多个点,此时ind是list(ind是此时点击到的点的编号)
if len(ind) > 1:
ind = ind[int(len(ind)/2)] # 多个点选中时,取中间点
# 或者像下面这样输出提示信息,让用户放大之后选
# print('Please zoom in to pick')
# return
x_axis = int((event.artist.get_xdata())[ind]) # 取到点的x轴坐标
# 记住不要在中文输入法pick操作,可能存在问题(例如会触发两次pick event)
if x_axis in self.picked: # pick已存在的点会触发消除操作
self.picked.remove(x_axis)
print('Remove point %d, picked: ' % x_axis, self.picked)
self.vlines[self.linedict[x_axis]].remove()
del self.vlines[self.linedict[x_axis]]
del self.linedict[x_axis]
plt.draw()
return
if len(self.picked) >= 2:
print( 'Too many points picked, picked: ', self.picked)
return
self.picked.append(x_axis)
print('Add point %d, picked: ' % x_axis, self.picked)
ax_line = ax.axvline(x_axis, color = 'black')
self.vlines.append(ax_line)
self.linedict[x_axis] = len(self.vlines) - 1
ele = {}
ele['type'] = 'line'
ele['ele'] = ax_line
ele['value'] = x_axis
self.steps.append(ele) # 记录这一步的操作,便于undo操作
plt.draw()
def StateSet(self, event): # 画垂直区域,key press event
if event.key == '0': # 重新画图
self._resetAx()
plt.draw()
print('Reset!')
return
if event.key == 'w': # 撤销上一步
self._undo()
plt.draw()
print('Undo last step, picked:', self.picked)
return
if len(self.picked) < 2: # 不会出现大于2的情况
print('Too less points selected, %d point(s) has been picked, picked' % len(self.picked), self.picked)
return
if event.key not in self.states: # 不在预设值的几个状态里面
return
self.state = event.key
self.start = min(self.picked)
self.end = max(self.picked)
color = { # 不同状态垂直区域标注不同颜色
'1': 'xkcd:light blue',
'2': 'xkcd:light green',
'3': 'xkcd:light purple',
}
span = ax.axvspan(self.start, self.end, facecolor = color[self.state], alpha=0.5) # alpha是透明度,0透明
self.vspans.append(span)
print(self.picked, 'is set to state %s' % self.state)
ele = {}
ele['type'] = 'span'
ele['ele'] = span
ele['start'] = self.start
ele['end'] = self.end
self.steps.append(ele)
self.picked = [] # 画完垂直区域后将picker清空
print('picked:', self.picked)
# 重新画图
plt.draw()
def _resetAx(self):
# for i in self.vspans:
# i.remove()
# for i in self.vlines:
# i.remove()
for i in self.steps:
i['ele'].remove()
self._reset()
def _undo(self): # 撤销上一步
if len(self.steps) == 0:
print('no more operation')
return
self.steps[-1]['ele'].remove()
if self.steps[-1]['type'] == 'line':
if self.steps[-1]['value'] in self.picked:
self.picked.remove(self.steps[-1]['value'])
elif self.steps[-1]['type'] == 'span': #如果撤销的是区域,需要将该区域的start和end加入到picked中去
self.picked = []
self.picked.append(self.steps[-1]['start'])
self.picked.append(self.steps[-1]['end'])
del self.steps[-1]
可执行代码如下
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
fig, ax = plt.subplots()
class MarkState(object):
def __init__(self):
self.start = 0 # 区域的起始点
self.end = 0 # 区域的结束点
self.state = 0 # 区域的状态
self.states = ['1', '2', '3'] # 接受的状态
self.picked = [] # 当前选择的点
self.vspans = [] # 垂直区域
self.vlines = [] # 垂直线
self.linedict = {} # 对应x轴坐标到vlines中的对应的index
self.steps = [] # 各个步骤(用于撤销操作)
def _reset(self): # 重置参数(重新画图)
self.linedict.clear()
self.vspans = []
self.vlines = []
self.picked = []
self.steps = []
def PointPick(self, event): # 画垂直线
ind = event.ind # 这里注意一点,当途中点击的点比较密集时,可能一次点击会选中多个点,此时ind是list(ind是此时点击到的点的编号)
if len(ind) > 1:
ind = ind[int(len(ind)/2)] # 多个点选中时,取中间点
# 或者像下面这样输出提示信息,让用户放大之后选
# print('Please zoom in to pick')
# return
x_axis = int((event.artist.get_xdata())[ind]) # 取到点的x轴坐标
# 记住不要在中文输入法pick操作,可能存在问题(例如会触发两次pick event)
if x_axis in self.picked: # pick已存在的点会触发消除操作
self.picked.remove(x_axis)
print('Remove point %d, picked: ' % x_axis, self.picked)
self.vlines[self.linedict[x_axis]].remove()
del self.vlines[self.linedict[x_axis]]
del self.linedict[x_axis]
plt.draw()
return
if len(self.picked) >= 2:
print( 'Too many points picked, picked: ', self.picked)
return
self.picked.append(x_axis)
print('Add point %d, picked: ' % x_axis, self.picked)
ax_line = ax.axvline(x_axis, color = 'black')
self.vlines.append(ax_line)
self.linedict[x_axis] = len(self.vlines) - 1
ele = {}
ele['type'] = 'line'
ele['ele'] = ax_line
ele['value'] = x_axis
self.steps.append(ele) # 记录这一步的操作,便于undo操作
plt.draw()
def StateSet(self, event): # 画垂直区域,key press event
if event.key == '0': # 重新画图
self._resetAx()
plt.draw()
print('Reset!')
return
if event.key == 'w': # 撤销上一步
self._undo()
plt.draw()
print('Undo last step, picked:', self.picked)
return
if len(self.picked) < 2: # 不会出现大于2的情况
print('Too less points selected, %d point(s) has been picked, picked' % len(self.picked), self.picked)
return
if event.key not in self.states: # 不在预设值的几个状态里面
return
self.state = event.key
self.start = min(self.picked)
self.end = max(self.picked)
color = { # 不同状态垂直区域标注不同颜色
'1': 'xkcd:light blue',
'2': 'xkcd:light green',
'3': 'xkcd:light purple',
}
span = ax.axvspan(self.start, self.end, facecolor = color[self.state], alpha=0.5) # alpha是透明度,0透明
self.vspans.append(span)
print(self.picked, 'is set to state %s' % self.state)
ele = {}
ele['type'] = 'span'
ele['ele'] = span
ele['start'] = self.start
ele['end'] = self.end
self.steps.append(ele)
self.picked = []
print('picked:', self.picked)
# 重新画图
plt.draw()
def _resetAx(self):
# for i in self.vspans:
# i.remove()
# for i in self.vlines:
# i.remove()
for i in self.steps:
i['ele'].remove()
self._reset()
def _undo(self): # 撤销上一步
if len(self.steps) == 0:
print('no more operation')
return
self.steps[-1]['ele'].remove()
if self.steps[-1]['type'] == 'line':
if self.steps[-1]['value'] in self.picked:
self.picked.remove(self.steps[-1]['value'])
elif self.steps[-1]['type'] == 'span': #如果撤销的是区域,需要将该区域的start和end加入到picked中去
self.picked = []
self.picked.append(self.steps[-1]['start'])
self.picked.append(self.steps[-1]['end'])
del self.steps[-1]
if __name__ == '__main__':
mark = MarkState()
fig.canvas.mpl_connect('pick_event', mark.PointPick)
fig.canvas.mpl_connect('key_press_event', mark.StateSet)
df = pd.DataFrame(np.random.randint(0,6,(1,14)), index=['x'])
# plot函数作图
tension = list(df.loc['x'])
data = list(range(14))
ax.plot(data, tension, 'o', picker=5)
ax.plot(data, tension, color='red', linewidth=1)
print(ax.lines)
plt.show()
实现效果如下
运行后生成
(某些原因图片无法上传,下次再传)