我想知道如何在matplotlib中动态更新堆积条形图。
这个问题Dynamically updating a bar plot in matplotlib描述了如何对普通条形图进行处理,而不是堆积条形图。
在普通条形图中,可以通过rect.set_height(h)
进行更新,假设rects = plt.bar(range(N), x, align='center')
但在堆积条形图中,我们还需要设置底部。
p2 = plt.bar(ind, womenMeans, width, color='y',
bottom=menMeans, yerr=menStd)
如何动态设置底部?不幸的是,似乎'Rectangle'对象没有属性'set_bottom'。有没有其他方法可以解决这个问题?
答案 0 :(得分:1)
出于某种原因,set_bottom()
所需的set_y
函数位于patches
的返回对象bar
下import numpy as np
import matplotlib.pyplot as plt
def setup_backend(backend='TkAgg'):
import sys
del sys.modules['matplotlib.backends']
del sys.modules['matplotlib.pyplot']
import matplotlib as mpl
mpl.use(backend) # do this before importing pyplot
import matplotlib.pyplot as plt
return plt
N = 5
width = 0.35 # the width of the bars: can also be len(x) sequence
def animate():
# http://www.scipy.org/Cookbook/Matplotlib/Animations
mu, sigma = 100, 15
h = mu + sigma * np.random.randn((N*2))
p1 = plt.bar(np.arange(N), h[:N], width, color='r')
p2 = plt.bar(np.arange(N), h[N:], width, color='b', bottom=h[:N])
assert len(p1) == len(p2)
maxh = 0.
for i in range(50):
for rect1, rect2 in zip(p1.patches, p2.patches):
h = mu + sigma * np.random.randn(2)
#Keep a record of maximum value of h
maxh = max(h[0]+h[1],maxh)
rect1.set_height(h[0])
rect2.set_y(rect1.get_height())
rect2.set_height(h[1])
#Set y limits to maximum value
ax.set_ylim((0,maxh))
fig.canvas.draw()
plt = setup_backend()
fig, ax = plt.subplots(1,1)
win = fig.canvas.manager.window
win.after(10, animate)
plt.show()
。最小的例子,基于你建议的链接,
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
} else {
gridView = (View) convertView;
}
gridView = inflater.inflate(R.layout.worker_listmain, null);
// your source code here!!! Run 100%
// I got this problem also, I found out the way to solve it!
// Please use my source code :D SIMPLE is PERFECT :D
return gridView;
}
注意,我在每次迭代时使用随机数更改高度生成,因此可以压缩两个补丁数组(否则会有点麻烦)。