2017-07-19 57 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