【问题标题】:Creating interactive Matplotlib histograms with Button widget使用 Button 小部件创建交互式 Matplotlib 直方图
【发布时间】:2014-07-21 19:28:02
【问题描述】:

我正在尝试使用 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 中创建的输出文件显示按钮正在工作并且我正在获取所需的数据。我只是无法让旧直方图消失并在其位置绘制新直方图。

非常感谢任何帮助/建议。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    在绘制新图之前,您需要清除旧图。您可以使用 plt.cla()plt.clf() 来做到这一点

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 2017-08-26
      • 2017-01-31
      • 2011-04-22
      相关资源
      最近更新 更多