You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib动画:如何显示静态圆并让点做圆周运动?

解决Matplotlib动画中静态圆不显示的问题

你编写的代码能实现点的圆周运动,但静态圆没显示,原因是创建的Circle对象没有添加到绘图坐标轴中。只需添加一行代码将圆加入坐标轴,同时可以简化update函数的返回值(因为圆是静态元素,不需要每次更新都返回)。

修正后的完整代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)

x, y = [], []
line, = plt.plot([], [], 'bo')
circle = plt.Circle((0,0), 1, color='g', fill=False)
# 关键:将静态圆添加到坐标轴
ax.add_patch(circle)

def update(frame):
    x.append(np.cos(frame))
    y.append(np.sin(frame))
    line.set_data(x, y)
    # 只返回动态更新的元素即可
    return line,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128), interval=10)
plt.show()

说明

  • ax.add_patch(circle):这行代码把创建的圆形补丁添加到坐标轴上,是静态圆能显示的核心步骤。
  • 原代码中interval=0.1数值过小,会导致动画速度过快且可能卡顿,建议改为interval=10(单位毫秒),让动画更流畅。
  • update函数只需返回动态变化的line对象,静态元素无需在返回值中重复声明。

内容的提问来源于stack exchange,提问作者박시현

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 17:31:57