簡體   English   中英

在matplotlib中動態更新堆積的條形圖

[英]Dynamically updating a stacked bar plot in matplotlib

我想知道如何在matplotlib中動態更新堆積的條形圖。

此問題在matplotlib動態更新條形圖描述了如何對普通條形圖而不是堆疊條形圖進行處理。

在正常的條形圖中,假設rects = plt.bar(range(N), x, align='center')可以通過rect.set_height(h)完成更新

但是在堆積的條形圖中,我們還需要設置底部。

p2 = plt.bar(ind, womenMeans, width, color='y',
             bottom=menMeans, yerr=menStd)

如何動態設置底部? 不幸的是,“矩形”對象似乎沒有屬性“ set_bottom”。 是否有其他方法可以解決此問題?

由於某些原因,您想要的set_bottom()函數位於bar返回對象中的patches下的set_y 基於您建議的鏈接的最小示例看起來像,

import numpy as np
import matplotlib.pyplot as plt

def setup_backend(backend='TkAgg'):
    import sys
    del sys.modules['matplotlib.backends']
    del sys.modules['matplotlib.pyplot']
    import matplotlib as mpl
    mpl.use(backend)  # do this before importing pyplot
    import matplotlib.pyplot as plt
    return plt

N = 5
width = 0.35       # the width of the bars: can also be len(x) sequence

def animate():
    # http://www.scipy.org/Cookbook/Matplotlib/Animations
    mu, sigma = 100, 15
    h = mu + sigma * np.random.randn((N*2))
    p1 = plt.bar(np.arange(N), h[:N], width, color='r')
    p2 = plt.bar(np.arange(N), h[N:], width, color='b', bottom=h[:N])
    assert len(p1) == len(p2)
    maxh = 0.
    for i in range(50):
        for rect1, rect2 in zip(p1.patches, p2.patches):
            h = mu + sigma * np.random.randn(2)
            #Keep a record of maximum value of h
            maxh = max(h[0]+h[1],maxh)
            rect1.set_height(h[0])
            rect2.set_y(rect1.get_height())
            rect2.set_height(h[1])
        #Set y limits to maximum value
        ax.set_ylim((0,maxh))
        fig.canvas.draw()

plt = setup_backend()
fig, ax = plt.subplots(1,1)
win = fig.canvas.manager.window
win.after(10, animate)
plt.show()

注意,我每次迭代都使用隨機數更改高度生成,因此可以壓縮兩個補丁數組(否則會有點混亂)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM