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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With