不断增长的matplotlib条形图 [英] Growing matplotlib bar charts
问题描述
我在matplotlib中有一个条形图,像这样:
I have a bar chart in matplotlib like this:
import numpy as np
import matplotlib.pyplot as plt
position = np.arange(6) + .5
plt.tick_params(axis = 'x', colors = '#072b57')
plt.tick_params(axis = 'y', colors = '#072b57')
rects = plt.bar(position, (0, 0, 0, 0, 0, 0), align = 'center', color = '#b8ff5c')
plt.xticks(position, ('A', 'B', 'C', 'D', 'E', 'F'))
plt.xlabel('X Axis', color = '#072b57')
plt.ylabel('Y Axis', color = '#072b57')
plt.title('My Chart', color = '#072b57')
plt.grid(True)
plt.show()
并且所有图表级别现在都为0,但是我想让图表中的每一列以不同的速度从0开始增长,直到它们全部达到最大值,例如100。 b $ b例如,在运行应用程序的过程中,图表如下所示:
and all the chart levels are at 0 now but I want to make each column in my chart grow from 0 with different speed until they all reach the maximum value which is for example 100. For example in the middle of running the application the chart would be like this:
,其余列仍会增长,直到它们全部达到最大值,然后程序将结束。
and the remaining columns still grow until they all reach the maximum value and then the program will finish.
现在我想问问matplotlib中有什么可以做这项工作吗?
Now I want to ask that is there anything in matplotlib to do this job?
推荐答案
是的,你可以做matplotlib中的动画,您需要使用 matplotlib.animation
查看此博客进行介绍。接下来,您将如何做您想要的事情?
Yes, you can do animations in matplotlib, you need to use matplotlib.animation
look at this blog for an introduction. Next how could you do what you want:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
fig = plt.figure()
position = np.arange(6) + .5
plt.tick_params(axis = 'x', colors = '#072b57')
plt.tick_params(axis = 'y', colors = '#072b57')
speeds = [1, 2, 3, 4, 1, 2]
heights = [0, 0, 0, 0, 0, 0]
rects = plt.bar(position, heights, align = 'center', color = '#b8ff5c')
plt.xticks(position, ('A', 'B', 'C', 'D', 'E', 'F'))
plt.xlabel('X Axis', color = '#072b57')
plt.ylabel('Y Axis', color = '#072b57')
plt.title('My Chart', color = '#072b57')
plt.ylim((0,100))
plt.xlim((0,6))
plt.grid(True)
rs = [r for r in rects]
def init():
return rs
def animate(i):
global rs, heights
if all(map(lambda x: x==100, heights)):
heights = [0, 0, 0, 0, 0, 0]
else:
heights = [min(h+s,100) for h,s in zip(heights,speeds)]
for h,r in zip(heights,rs):
r.set_height(h)
return rs
anim = animation.FuncAnimation(fig, animate, init_func=init,frames=200, interval=20, blit=True)
plt.show()
这篇关于不断增长的matplotlib条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!