[英]How to update barchart in 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(),我的所有設置(線寬,邊緣顏色,標題..)不僅會丟失數據(矩形),而且會丟失很多次並重置所有內容,這會使我的程序步履蹣跚。 如果我不使用ax.cla()
,則設置會保留,程序會更快(我不必一直設置屬性),但是矩形是相互繪制的,這不好。
你能幫我嗎?
在您的情況下, bars
只是BarContainer
,它基本上是Rectangle
修補程序的列表。 要在保留ax
所有其他屬性的同時刪除它們,可以在bars容器上循環並對其所有條目調用remove,或者如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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.