如何通过matplotlib响应鼠标点击事件来制作我的图形?

时间:2018-04-12 04:14:45

标签: matplotlib python-interactive

我阅读matplotlib的文档并编写以下代码,它应该捕获我的鼠标事件并在我点击时移动灰线位置。我在jupiter notebook在线阅读这段代码,它停止显示光标的坐标,就像它通常那样,发生了什么?任何人都可以帮助我吗?

import pandas as pd
import numpy as np
import matplotlib.colors as mcol
import matplotlib.cm as cm
from scipy import stats
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt 
import scipy.spatial as spatial
np.random.seed(12345)

df = pd.DataFrame([np.random.normal(33500,150000,3650), 
                   np.random.normal(41000,90000,3650), 
                   np.random.normal(41000,120000,3650), 
                   np.random.normal(48000,55000,3650)], 
                  index=[1992,1993,1994,1995])

fig, ax = plt.subplots()

year_avg = df.mean(axis = 1)
year_std = df.std(axis = 1)
yerr = year_std / np.sqrt(df.shape[1]) * stats.t.ppf(1-0.05/2, df.shape[1]-1)

bars=ax.bar(range(df.shape[0]), year_avg, yerr = yerr, color = 'lightslategrey')
threshold=42000
line=plt.axhline(y = threshold, color = 'grey', alpha = 0.5)

cm1 = mcol.LinearSegmentedColormap.from_list("CmapName",["yellow", "orange", "red"])
cpick = cm.ScalarMappable(cmap=cm1)
percentages = []
cpick.set_array([])
def setColor(bars, yerr,threshold):
    for bar, yerr_ in zip(bars, yerr):
        low = bar.get_height() - yerr_
        high = bar.get_height() + yerr_
        percentage = (high-threshold)/(high-low)
        if percentage>1: percentage = 1
        if percentage<0: percentage=0
        percentages.append(percentage)
    cpick.to_rgba(percentages)
    bars = ax.bar(range(df.shape[0]), year_avg, yerr = yerr, color = cpick.to_rgba(percentages))
    return bars
line=plt.axhline(threshold, color = 'grey', alpha = 0.5)

setColor(bars, yerr,threshold)
plt.colorbar(cpick, orientation='horizontal')
plt.xticks(range(df.shape[0]), df.index)
fig = plt.figure()
plt.show()

def onclick(event):
    print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
          ('double' if event.dblclick else 'single', event.button,
           event.x, event.y, event.xdata, event.ydata))
    line.set_ydata(event.ydata)
    #plt.draw()
cid = fig.canvas.mpl_connect('button_press_event', onclick)

0 个答案:

没有答案