【问题标题】:Updating a matplotlib bar graph?更新 matplotlib 条形图?
【发布时间】:2012-03-18 09:08:40
【问题描述】:

我有一个条形图,它从字典中检索它的 y 值。我不需要显示具有所有不同值的多个图表并且我必须关闭每一个图表,而是需要它来更新同一个图表上的值。有解决方案吗?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    以下是如何为条形图设置动画的示例。 你只调用一次plt.bar,保存返回值rects,然后调用rect.set_height修改条形图。 调用fig.canvas.draw() 会更新图形。

    import matplotlib
    matplotlib.use('TKAgg')
    import matplotlib.pyplot as plt
    import numpy as np
    
    def animated_barplot():
        # http://www.scipy.org/Cookbook/Matplotlib/Animations
        mu, sigma = 100, 15
        N = 4
        x = mu + sigma*np.random.randn(N)
        rects = plt.bar(range(N), x,  align = 'center')
        for i in range(50):
            x = mu + sigma*np.random.randn(N)
            for rect, h in zip(rects, x):
                rect.set_height(h)
            fig.canvas.draw()
    
    fig = plt.figure()
    win = fig.canvas.manager.window
    win.after(100, animated_barplot)
    plt.show()
    

    【讨论】:

    • 如果我们需要在每次更新时向图表添加新的条形怎么办?另外, fig.canvas.draw() 与使用 FuncAnimation 相比如何?
    【解决方案2】:

    我已将上述出色的解决方案简化为基本要素,更多详细信息请访问我的blogpost

    import numpy as np
    import matplotlib.pyplot as plt
    
    numBins = 100
    numEvents = 100000
    
    file = 'datafile_100bins_100000events.histogram'
    histogramSeries = np.loadtext(file)
    
    fig, ax = plt.subplots()
    rects = ax.bar(range(numBins), np.ones(numBins)*40)  # 40 is upper bound of y-axis 
    
    for i in range(numEvents):
        for rect,h in zip(rects,histogramSeries[i,:]):
            rect.set_height(h)
        fig.canvas.draw()
        plt.pause(0.001)
    

    【讨论】:

    • @stochastic 你有时间保存动画吗?
    • @László 我作弊并拍摄桌面视频,因为我不需要高质量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    相关资源
    最近更新 更多