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

如何使用matplotlib实现3x+1模拟数据的实时连线绘制

问题根因

  • 你在循环中每次调用plt.plot()仅传入单个x、y坐标,matplotlib无法为孤立的单点生成连线,最终只会显示所有独立的点标记
  • 用plots.index(i)获取x坐标存在逻辑缺陷:如果3x+1计算序列中出现重复数值,该方法会始终返回第一个匹配项的索引,导致坐标错位

修复方案

维护动态增长的坐标序列,每次新增点后绘制截止到当前点的完整序列,即可实现实时出现点、同时自动连接前后点的效果。你可以参考以下修改后的代码:

import matplotlib.pyplot as plt
plots = []

def three(x):
    if x == 1:
        return x
    if x % 2 == 0:
        next_val = x / 2
    else:
        next_val = 3 * x + 1
    plots.append(next_val)
    return three(next_val)

num = int(input('Number: '))
plots.append(num)
three(num)

# 开启matplotlib交互模式
plt.ion()
fig, ax = plt.subplots()
# 预先创建空线条对象,后续仅更新数据即可,性能更高
line, = ax.plot([], [], ".-")
x_coords = []
y_coords = []

for idx, val in enumerate(plots):
    x_coords.append(idx + 1)
    y_coords.append(val)
    # 更新线条数据
    line.set_data(x_coords, y_coords)
    # 自动适配坐标轴范围
    ax.relim()
    ax.autoscale_view()
    plt.pause(0.05)

# 关闭交互模式,保留最终绘图窗口
plt.ioff()
plt.show()

如果你的测试序列较短,也可以用每次清空重绘的简单写法,逻辑更直观:

import matplotlib.pyplot as plt
plots = []

def three(x):
    if x == 1:
        return x
    if x % 2 == 0:
        next_val = x / 2
    else:
        next_val = 3 * x + 1
    plots.append(next_val)
    return three(next_val)

num = int(input('Number: '))
plots.append(num)
three(num)

plt.ion()
x_coords = []
y_coords = []

for idx, val in enumerate(plots):
    x_coords.append(idx + 1)
    y_coords.append(val)
    plt.cla()
    plt.plot(x_coords, y_coords, ".-")
    plt.pause(0.05)

plt.ioff()
plt.show()

内容的提问来源于stack exchange,提问作者Pedro Paulo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:54:03