2017-04-12 50 views
1

我想要有幾個子圖,其中兩個顯示來自視頻源的幀,第三個顯示計算結果作爲條形圖。 創建matplotlib圖後,我創建了幾個subplot2grid,然後使用FuncAnimation進行更新。subplot2grid中的條形圖

我想創建一個條形圖(待更新),通常的方法是:

fig = plt.figure() 
ax = plt.axes(xlim=(0, 9), ylim=(0, 100)) 
rects = plt.bar(res_x, res_y, color='b') 

def animate(args): 
    ... 
    ... 
    for rect, yi in zip(rects, results): 
     rect.set_height(yi*100) 
    return rects 

anim = animation.FuncAnimation(fig, animate, frames=200, interval=20, blit=True) 
plt.show() 

我現在想加沿一側的條形圖其他次要情節:

fig = plt.figure() 
plt1 = plt.subplot2grid((2, 2), (0, 0), rowspan=2) 
plt2 = plt.subplot2grid((2, 2), (0, 1)) 

#Confusion with the following 
bar_plot = plt.subplot2grid((2,2), (1,1)) 
ax = plt.axes(xlim=(0, 9), ylim=(0, 100)) 
rects = plt.bar(res_x, res_y, color='b') 


def animate(args): 
    ... 
    ... 

    im1 = plt1.imshow(...) 
    im2 = plt2.imshow(...) 

    for rect, yi in zip(rects, results): 
     rect.set_height(yi*100) 
    return im1, im2, rects 

anim = animation.FuncAnimation(fig, animate, frames=200, interval=20, blit=True) 
plt.show() 

我得到以下錯誤:AttributeError:'BarContainer'對象沒有屬性'set_animated'

任何想法如何「放置」一個條形圖作爲一個子圖,並與其他數據一起更新fr ü子圖?

謝謝!

回答

1

錯誤來自行return im1, im2, rects

雖然在工作的解決方案,你有return rects,即返回其中有一個set_animated方法藝術家列表。在失敗的代碼中,您有一個BarContainer和兩個藝術家的元組。如錯誤所示,AttributeError:'BarContainer'對象沒有屬性'set_animated'

解決方案可能是生成BarContainer的內容列表,您可以將它連接到其他兩位藝術家。

return [rect for rect in rects]+[im1, im2] 

一個完整的工作示例:

import matplotlib.pyplot as plt 
import matplotlib.animation as animation 

res_x, res_y = [1,2,3], [1,2,3] 

fig = plt.figure() 
ax = plt.subplot2grid((2, 2), (0, 0), rowspan=2) 
ax2 = plt.subplot2grid((2, 2), (0, 1)) 
ax3 = plt.subplot2grid((2,2), (1,1)) 

rects = ax3.bar(res_x, res_y, color='b') 
im1 = ax.imshow([[1,2],[2,3]], vmin=0) 
im2 = ax2.imshow([[1,2],[2,3]], vmin=0) 

def animate(i): 

    im1.set_data([[1,2],[(i/100.),3]]) 
    im2.set_data([[(i/100.),2],[2.4,3]]) 

    for rect, yi in zip(rects, range(len(res_x))): 
     rect.set_height((i/100.)*(yi+0.2)) 
    return [rect for rect in rects]+[im1, im2] 

anim = animation.FuncAnimation(fig, animate, frames=200, interval=20, blit=True) 
plt.show() 
+0

@dtam如果這個回答你的問題,你應該考慮[接受](https://meta.stackexchange.com/questions/5234/how-does接受答案的工作)。如果沒有,您可以通過更新您的問題來提供更多詳細信息。如果答案有幫助(假設它解決了問題,那麼你也可以考慮加註)。當然,這同樣適用於你的老問題([here](http://stackoverflow.com/questions/43099734/combining-cv2-imshow-with-matplotlib-plt-show-in-real-time)和[here ](http://stackoverflow.com/questions/43372792/matplotlib-opencv-image-subplot))。 – ImportanceOfBeingErnest

+0

使用此解決方案時出現以下錯誤: 「AttributeError:draw_artist只能在初始繪製緩存渲染後使用」 此外,這打開了條形圖的繪圖,但覆蓋了其他兩個子繪圖,而I希望所有三個人都可以成爲次要情節,並將他們看在一起。任何想法? 我很抱歉不接受以前的,我現在就去找他們。 – dtam

+0

由於您沒有顯示完整的代碼,因此無法知道此錯誤來自何處。但是我在答案中加了一個[mcve],這表明它按預期工作。 – ImportanceOfBeingErnest