首页 > 解决方案 > 动态更新饼图

问题描述

我每秒都在接收数据,我需要用接收到的每个数据更新同一个饼图。我阅读了一些论坛并有一个代码。然而,目前每个接收值,我得到另一个饼图,即之前的饼图值没有被刷新。我想刷新相同的饼图值

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
labels=['a','b']
def animate(i):
    nums=[x1,x2]
    ax.clear()
    ax1.pie(nums, labels=labels, 
                    autopct='%1.1f%%', shadow=True, startangle=140)
            
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()

的价值x1x2不断变化。所有这些都在一个for loop监听新数据的内部x1x2 我在做什么错?

标签: pythonmatplotlib

解决方案


请检查片段。这将每 2 秒更新一次图表。

您可以调用plt.pause(2)来绘制新数据并运行 GUI 的事件循环

import random
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
labels=['a','b']
for i in range(10):    
    nums=[random.randint(5,10),random.randint(5,10)]
    ax1.clear()
    ax1.pie(nums, labels=labels, autopct='%1.1f%%', shadow=True, startangle=140)
    plt.pause(2)
plt.draw()

推荐阅读