如何在matplotlib中更新条形图?

8

我有一个条形图,带有许多自定义属性(标签,线宽,边框颜色)。

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(),设置会保留,程序会更快(我不必一直设置属性),但是矩形会相互绘制,这是不好的。

你能帮我解决这个问题吗?

1个回答

8
在您的情况下,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()

1
为什么要逐个删除柱形图而不直接删除整个BarContainer,"bars.remove()"? - ImportanceOfBeingErnest
我已经尝试了你的解决方案:循环遍历“bars”,并一步删除“bars”。在新的ax.bar(x2,y2)之后,矩形再次变为蓝色,但我的其他设置(当然不是与矩形相关的设置),如标题、y、x限制保持不变,谢谢! - user3598726

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接