Python中的饼图动画 [英] Pie Chart animation in Python

查看:41
本文介绍了Python中的饼图动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中制作一个饼图动画,它会根据数据不断变化(通过循环不断变化).问题在于它正在一张一张地打印每个饼图,而我最终却拥有许多饼图.我希望更改一个饼图,使其看起来像一个动画.知道怎么做吗?

I want to make a pie chart animation in python where it will be changing continuously according to the data (which is being changed continuously through loop). The problem is that it is printing every pie chart one by one and I end up having many pie charts. I want one pie chart to change in place so that it seems like an animation. Any idea how to do this?

我正在使用以下代码

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

推荐答案

您可能想要使用 FuncAnimation.不幸的是,饼图本身没有更新功能.虽然可以用新数据更新楔形,但这似乎相当麻烦.因此,在每个步骤中清除轴并为其绘制新的饼图可能会更容易.

You would want to use a FuncAnimation. Unfortunately the pie chart has no updating function itself; while it would be possible to update the wedges with new data, this seems rather cumbersome. Hence it might be easier to clear the axes in each step and draw a new pie chart to it.

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

这篇关于Python中的饼图动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆