我的代码发生了奇怪的事情,我正在学习如何使用matplotlib创建图,并且我有以下示例:
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import datetime as dt
import numpy as np
import matplotlib.dates as md
from matplotlib.widgets import Button
def graph():
#x = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,19,19,19,19]
#xm =[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,21,38,47,55]
x = [dt.datetime(2018, 7, 7, 17, 59), dt.datetime(2018, 7, 7, 18, 4), dt.datetime(2018, 7, 7, 19, 9),
dt.datetime(2018, 7, 7, 19, 14), dt.datetime(2018, 7, 7, 20, 19), dt.datetime(2018, 7, 7, 20, 24),
dt.datetime(2018, 7, 7, 20, 29), dt.datetime(2018, 7, 7, 21, 34), dt.datetime(2018, 7, 7, 21, 39),
dt.datetime(2018, 7, 7, 22, 44)]
y = [72,68,145,156,184,160,210,230,215,222]
highest = max(y)
lowest = min(y)
#datetimes = [datetime.time.strptime(t, "%H:%M") for t in x]
#datetimes = []
#s = 0
#for t in x:
# datetimes.append(datetime.time(t,xm[s]).isoformat(timespec='minutes'))
# s += 1
#plt.axhline(lowest, color='c', linestyle='--', label='Last 24h min Comsumption')
#plt.text(24.4, lowest, str(lowest), va='center', ha="left", bbox=dict(facecolor="w",alpha=0.5))
#plt.axhline(highest, color='r', linestyle='--', label='Last 24h max Comsumption')
#plt.text(24.4, highest, str(highest), va='center', ha="left", bbox=dict(facecolor="w",alpha=0.5))
xlen = len(x)
lastdate = xlen - 1
deltah = dt.timedelta(minutes = 17)
figfuel, ax = plt.subplots()
ax.plot(x,y, label ='Cb-Ft per hour')
ax.axhline(highest, color='r', linestyle='--', label='Last 24h max Comsumption')
ax.text(x[lastdate] + deltah, highest, str(highest), va='center', ha="left", bbox=dict(facecolor="w",alpha=0.5))
ax.axhline(lowest, color='c', linestyle='--', label='Last 24h min Comsumption')
ax.text(x[lastdate] + deltah, lowest, str(lowest), va='center', ha="left", bbox=dict(facecolor="w",alpha=0.5))
#plt.plot(x,y, label='Cb-Ft per hour')
#plt.connect('button_press_event', efecto)
plt.subplots_adjust(bottom=0.2)
plt.ylabel('Fuel Comsumption (Cb-ft per hour)')
plt.title('Fuel Comsumption Chart')
plt.grid(True)
plt.legend()
plt.xticks(rotation=90)
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
xformatter = md.DateFormatter('%H:%M')
xlocator = md.MinuteLocator(byminute=[0,60], interval = 1)
ax.xaxis.set_major_locator(xlocator)
plt.gcf().axes[0].xaxis.set_major_formatter(xformatter)
#axcut = plt.axes([0.7, 0.05, 0.1, 0.075])
axcut = plt.axes([0.885, 0.015, 0.1, 0.075])
bcut = Button(axcut, 'Close')
bcut.on_clicked(efecto)
plt.show()
def efecto(event):
plt.close()
正如您所看到的,我注释了很多行,因为当时我正在测试,graph()函数由另一个外部脚本调用,所以问题出在下面,在第二行,您可以看到我设置了后端是Qt5Agg,因此当我执行该操作时,在文件末尾创建的按钮停止工作,它什么也不做,当鼠标指针悬停在它上面时不突出显示,并且单击它时什么也没有发生。但是,如果我注释了matplotlib.use行,则脚本将使用默认脚本(TkAgg),然后该按钮将正常工作,如果将鼠标指针放在其上,它将更改颜色,如果单击该按钮,情节变得封闭,所以我在做错什么?,我试图读取有关后端的差异,但没有发现与按钮相关的任何内容。