Python中的饼图动画

时间:2017-11-17 20:33:12

标签: python python-3.x python-2.7 matplotlib

我想在python中制作一个饼图动画,它将根据数据(通过循环不断更改)不断变化。问题在于它逐个打印每个饼图,最终我得到了很多饼图。我想要一个饼图改变到位,这样它看起来像一个动画。知道怎么做吗?

我正在使用以下代码

colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'black', 'red', 'navy', 'blue', 'magenta', 'crimson']
explode = (0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, .01)
labels = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
nums = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

for num in range(1000):
    str_num = str(num)
    for x in range(10):
        nums[x] += str_num.count(str(x))
    plt.pie(nums, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)
    plt.axis('equal')
    plt.show()

1 个答案:

答案 0 :(得分:2)

您可能想要使用FuncAnimation。不幸的是,饼图本身没有更新功能;虽然可以用新数据更新楔子,但这看起来相当麻烦。因此,在每个步骤中清除轴并向其绘制新的饼图可能更容易。

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'limegreen', 
          'red', 'navy', 'blue', 'magenta', 'crimson']
explode = (0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, .01)
labels = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
nums = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

fig, ax = plt.subplots()

def update(num):
    ax.clear()
    ax.axis('equal')
    str_num = str(num)
    for x in range(10):
        nums[x] += str_num.count(str(x))
    ax.pie(nums, explode=explode, labels=labels, colors=colors, 
            autopct='%1.1f%%', shadow=True, startangle=140)
    ax.set_title(str_num)

ani = FuncAnimation(fig, update, frames=range(100), repeat=False)
plt.show()

enter image description here