Gad*_*eek 4 python matplotlib python-2.7 python-3.x
我想在 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()
Run Code Online (Sandbox Code Playgroud)
Imp*_*est 14
你会想要使用一个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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3760 次 |
| 最近记录: |