use*_*726 6 python plot matplotlib bar-chart
我有条形图,有很多自定义属性(标签、线宽、边缘颜色)
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()
Run Code Online (Sandbox Code Playgroud)
我会使用“正常”图set_data(),但使用条形图时出现错误:AttributeError: 'BarContainer' object has no attribute 'set_data'
我不想简单地更新矩形的高度,我想绘制全新的矩形。如果我使用 ax.cla(),我的所有设置(线宽、边缘颜色、标题..)都会丢失,不仅是我的数据(矩形),而且要多次清除和重置所有内容都会使我的程序滞后。如果我不使用ax.cla(),设置保留,程序更快(我不必一直设置我的属性),但是矩形是相互绘制的,这不好。
你能帮我解决这个问题吗?
在您的情况下,bars只是 a BarContainer,它基本上是Rectangle补丁列表。要在保留 的所有其他属性的同时删除那些ax,您可以遍历 bar 容器并对其所有条目调用 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()
Run Code Online (Sandbox Code Playgroud)