【问题标题】:Growing matplotlib bar charts不断增长的 matplotlib 条形图
【发布时间】:2017-06-01 08:16:06
【问题描述】:

我在 matplotlib 中有一个这样的条形图:

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。 例如,在运行应用程序的过程中,图表将如下所示:

剩余的列仍然会增长,直到它们都达到最大值,然后程序将结束。

现在我想问一下matplotlib中有什么东西可以做这个工作吗?

【问题讨论】:

    标签: python charts matplotlib


    【解决方案1】:

    是的,你可以在matplotlib中做动画,你需要使用matplotlib.animationthis blog的介绍。接下来你怎么能做你想做的事:

    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()
    

    【讨论】:

    • 谢谢,这太棒了(:
    【解决方案2】:

    您添加了 highcharts 标签。因此,在 highcharts 中,您可以使用每个系列的 animation 属性来完成。我制作了 3 个系列,每个系列都有一个栏,并更改了每个系列的动画速度:

    series: [{
        name: 'Tokyo',
        data: [100, 0, 0],
        animation: {
            duration: 1000
        }
    }, {
        name: 'NYC',
        data: [0, 100, 0],
        animation: {
            duration: 3000
        }
    }, {
        name: 'Berlin',
        data: [0, 0, 100],
        animation: {
            duration: 7000
        }
    }]
    

    例如jsFiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 2016-01-02
      • 1970-01-01
      • 2017-03-27
      相关资源
      最近更新 更多