Pie Chart animation in Python

巧了我就是萌 提交于 2020-12-01 12:06:06

问题


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?

I am using the following the code

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:


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



来源:https://stackoverflow.com/questions/47358835/pie-chart-animation-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!