2017-07-19 124 views
2

我有條形圖,有很多自定義屬性(標籤,線寬,edgecolor)如何更新matplotlib中的條形圖?

import matplotlib.pyplot as plt 
fig = plt.figure() 
ax = plt.gca() 

x = np.arange(5) 
y = np.random.rand(5) 

bars = ax.bar(x, y, color='grey', linewidth=4.0) 

ax.cla() 
x2 = np.arange(10) 
y2 = np.random.rand(10) 
ax.bar(x2,y2) 
plt.show() 

用「正常」的情節我會用set_data()的,但與條形圖我得到了一個錯誤:AttributeError: 'BarContainer' object has no attribute 'set_data'

我不想簡單地更新矩形的高度,我想繪製全新的矩形。如果我使用ax.cla(),我所有的設置(linewidth,edgecolor,title ..)都會丟失,不僅我的數據(矩形)和清除很多次,以及重置所有設置都會使我的程序不穩定。如果我不使用ax.cla(),則設置保持不變,程序速度更快(我不必始終設置屬性),但矩形相互繪製,這不太好。

你能幫我嗎?

回答

3

在你的情況下,bars只是一個BarContainer,它基本上是一個Rectangle補丁列表。只刪除那些同時保持ax所有其他屬性,可以遍歷所有的酒吧容器,並呼籲取消對所有條目或ImportanceOfBeingErnest指出,簡單地刪除完整的容器:

import numpy as np 
import matplotlib.pyplot as plt 
fig = plt.figure() 
ax = plt.gca() 

x = np.arange(5) 
y = np.random.rand(5) 

bars = ax.bar(x, y, color='grey', linewidth=4.0) 

bars.remove() 
x2 = np.arange(10) 
y2 = np.random.rand(10) 
ax.bar(x2,y2) 
plt.show() 
+0

爲什麼取出的酒吧之一,由並且不直接刪除完整的BarContainer,bars.remove()'? – ImportanceOfBeingErnest

+0

我已經嘗試過你的解決方案:循環thrugh'酒吧',並刪除一步也bars.After新的ax.bar(x2,y2)矩形再次藍色,但我的其他設置(非矩形相關的當然),像標題一樣,y,x lims保持不變,謝謝! – user3598726