H4iku
H4iku

Reputation: 672

Growing matplotlib bar charts

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

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: enter image description here

and the remaining columns still grow until they all reach the maximum value and then the program will finish.

Now I want to ask that is there anything in matplotlib to do this job?

Upvotes: 1

Views: 2130

Answers (2)

wergeld
wergeld

Reputation: 14462

You added highcharts tag. So, in highcharts you would do it with the animation properties on each series. I made 3 series, each with one bar and changed the animation speed on each:

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
    }
}]

Example jsFiddle.

Upvotes: 1

Alvaro Fuentes
Alvaro Fuentes

Reputation: 17485

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

Upvotes: 2

Related Questions