【问题标题】:Pie Chart animation in PythonPython中的饼图动画
【发布时间】:2018-05-01 17:07:46
【问题描述】:

我想在 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()

【问题讨论】:

  • 大家不要对这个问题投反对票,如果您想要更多详细信息,请在评论中提问。
  • 你试过使用 Matplotlib 的 animation module 吗? This example 在 animate 函数的每个循环上使用新数据更新轴图可能与您要查找的内容接近。
  • 谢谢@StevenWalton。看来这就是我要找的东西。

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


【解决方案1】:

您可能想使用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()

【讨论】:

  • 太好了,帮了我很多:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
相关资源
最近更新 更多