我正在使用绘制一个时间序列,pyplot
并希望在选定一个点后突出显示该点(使用pick_event
)。在这里发现了类似的问题,但无法解决。这是我做的一个简单的例子:
import matplotlib.pyplot as plt
class MyPlot(object):
def __init__(self, parent=None):
super(self.__class__, self).__init__()
def makePlot(self):
fig = plt.figure('Test', figsize=(10, 8))
ax = plt.subplot(111)
x = range(0, 100, 10)
y = (5,)*10
ax.plot(x, y, '-', color='red')
ax.plot(x, y, 'o', color='blue', picker=5)
plt.connect('pick_event', self.onPick)
plt.show()
def onPick(self, event=None):
this_point = event.artist
x_value = this_point.get_xdata()
y_value = this_point.get_ydata()
ind = event.ind
print 'x:{0}'.format(x_value[ind][0])
print 'y:{0}'.format(y_value[ind][0])
if __name__ == '__main__':
app = MyPlot()
app.makePlot()
Run Code Online (Sandbox Code Playgroud)
选定的点将被标记(例如,通过将其变为黄色),但是当我选择另一个点时,应将其重置为蓝色,并且仅高亮显示新选择的点(没有注释,只是颜色改变)。我怎样才能做到这一点?
您可以定义一个新的图(黄色),在开始时为空。单击一个点后,将该图的数据更改为所选点的数据,然后重新绘制画布。
import matplotlib.pyplot as plt
class MyPlot(object):
def makePlot(self):
self.fig = plt.figure('Test', figsize=(10, 8))
ax = plt.subplot(111)
x = range(0, 100, 10)
y = (5,)*10
ax.plot(x, y, '-', color='red')
ax.plot(x, y, 'o', color='blue', picker=5)
self.highlight, = ax.plot([], [], 'o', color='yellow')
self.cid = plt.connect('pick_event', self.onPick)
plt.show()
def onPick(self, event=None):
this_point = event.artist
x_value = this_point.get_xdata()
y_value = this_point.get_ydata()
ind = event.ind
self.highlight.set_data(x_value[ind][0],y_value[ind][0])
self.fig.canvas.draw_idle()
if __name__ == '__main__':
app = MyPlot()
app.makePlot()
Run Code Online (Sandbox Code Playgroud)