使用按钮组件创建交互式Matplotlib直方图
我正在尝试使用Matplotlib来创建一个互动图表。我希望每次按下一个图形按钮时,能够切换到一组不同的图表。不过,尽管我的按钮看起来可以用,但我就是无法让图表重新绘制。我查阅了网上的例子,但还是没能找到我缺少的部分。
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy as np
curr = 0
avgData = None
...
def prev(event):
#Use '<' button to get prior histogram
global curr
curr -= 1
reset()
def next(event):
#Use '>' button to get next histogram
global curr
curr += 1
reset()
def reset():
#Get data for new graph and draw/show it
global curr
global avgData
#Stay within bounds of number of histograms
if curr < 0:
curr = 0
elif curr >= len(avgData):
curr = len(avgData) - 1
#Get info for new histogram
bins, hist, hist2, barWidth = getHistParams(avgData[curr])
#Verify code got here and obtained data for next histogram
f=open('reset.txt','a')
f.write(str(curr))
f.write(str(hist2))
f.write("\n==========================================================\n")
f.close()
#Try to draw
plt.figure(1)
rects = plt.bar(bins,hist2,width=barWidth,align='center')
plt.draw()
def plotHistGraphs(avg):
#Create initial plot
#Get initial data
bins, hist, hist2, calcWidth = getHistParams(avg)
#Create plot
plt.figure(1)
rects = plt.bar(bins,hist2,width=calcWidth,align='center')
plt.xlabel("Accuracy of Classifiers")
plt.ylabel("% of Classifiers")
plt.title("Histogram of Classifier Accuracy")
#Create ">"/"Next" Button
histAxes1 = plt.axes([0.055, 0.04, 0.025, 0.04])
histButton1 = Button(histAxes1, ">", color = 'lightgoldenrodyellow', hovercolor = '0.975')
histButton1.on_clicked(next)
#Create "<"/"Prev" Button
histAxes2 = plt.axes([0.015, 0.04, 0.025, 0.04])
histButton2 = Button(histAxes2, "<", color = 'lightgoldenrodyellow', hovercolor = '0.975')
histButton2.on_clicked(prev)
plt.show()
我试过各种组合,比如plt.show、plt.draw和plt.ion,但还是无法让它正常工作。我在函数reset中创建的输出文件显示按钮是有效的,并且我得到了需要的数据。可我就是无法让旧的直方图消失,替换成新的直方图。
任何帮助或建议都非常感谢。
1 个回答
1
在画新的图之前,你需要先把旧的图清除掉。你可以使用 plt.cla()
和 plt.clf()
来做到这一点。