如何更新 matplotlib 中的条形图?

2023-11-24

我有条形图,有很多自定义属性(标签、线宽、边缘颜色)

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,您可以循环遍历 bar 容器并对其所有条目调用删除,或者正如“认真的重要性”所指出的那样,只需删除整个容器:

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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何更新 matplotlib 中的条形图? 的相关文章

随机推荐