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

如何在Python中为单张图批量添加多组数据集?

解决多组数据集批量绘图的问题

当然有办法处理任意数量的数据集,核心就是用循环替代硬编码的重复plot调用,不管你是20组还是100组,都能自动完成绘图。

修正后的完整代码

首先注意你的代码里matplotlib导入有误,应该是import matplotlib.pyplot as plt,否则无法正常调用绘图接口。下面是优化后的代码:

import numpy as np
import matplotlib.pyplot as plt  # 修正导入方式

N_steps = 1000
N_plot = 20  # 后续改成100直接改这个值就行
xorb_list = np.empty((N_plot, N_steps))
yorb_list = np.empty((N_plot, N_steps))
xobs = np.empty((N_plot, N_steps))
yobs = np.empty((N_plot, N_steps))
zobs = np.empty((N_plot, N_steps))

# 假设r、cm_to_arcsec、cos_theta等变量已提前定义
for i in range(N_plot):
    for k in range(N_steps):
        xorb_list[i][k] = r[k] * cm_to_arcsec * cos_theta[k]
        yorb_list[i][k] = r[k] * cm_to_arcsec * sin_theta[k]
        xobs[i][k] = r[k] * (cos_lon * cos_w_plus_nu[k] - sin_lon * sin_w_plus_nu[k] * cos_i)
        yobs[i][k] = r[k] * (sin_lon * cos_w_plus_nu[k] + cos_lon * sin_w_plus_nu[k] * cos_i)
        zobs[i][k] = r[k] * sin_i * sin_w_plus_nu[k]

# 绘制观测轨道
fig1 = plt.figure(1)
ax1 = fig1.add_subplot()
ax1.set_aspect(1)
ax1.set_title("Observed Stellar Orbits")

# 用循环替代20行硬编码的plot
for i in range(N_plot):
    ax1.plot(xobs[i], yobs[i])

# 可选:如果需要每条曲线带标签,可修改循环为
# for i in range(N_plot):
#     ax1.plot(xobs[i], yobs[i], label=f"Orbit {i+1}")
# ax1.legend()  # 显示图例

plt.show()

关键优化点

  • 把原来20行重复的ax1.plot(xobs[n], yobs[n])改成一个for循环,遍历0到N_plot-1的索引,自动处理所有数据集。
  • 后续要增加到100组数据,只需要把N_plot的值改成100,循环会自动适配,不需要修改绘图部分的代码。
  • 如果需要区分不同轨道,可以在循环里添加label参数并调用ax1.legend(),方便识别每条曲线。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 11:54:14