如何在Matplotlib中生成独立折线图及合并折线图(非子图)
解决方案
直接修改代码,在循环中同时生成独立单图和合并图,无需存储大数据集:
import matplotlib.pyplot as plt import numpy as np # 提前创建合并图的画布和坐标轴 combined_fig, combined_ax = plt.subplots() for i in range(2): x = np.arange(0, 4*np.pi, 0.1) y = np.sin(x) current_y = i*y + i line_label = f"折线{i+1}" # 生成独立的单图窗口 plt.figure() # 每次循环创建新画布,保证单图独立 plt.plot(x, current_y) plt.title(f"单图:折线{i+1}") plt.xlabel("x") plt.ylabel("y") plt.show(block=False) # 避免阻塞后续代码执行 # 在合并图中添加当前折线 combined_ax.plot(x, current_y, label=line_label) # 配置合并图并显示 combined_ax.set_title("合并图:所有折线") combined_ax.set_xlabel("x") combined_ax.set_ylabel("y") combined_ax.legend() # 显示图例 plt.show()
关键说明:
- 用
plt.figure()在每次循环中创建新画布,确保每张单图都是独立窗口 - 提前初始化合并图的坐标轴,循环中直接复用该坐标轴绘图,不需要将大数据集存入列表,避免额外内存占用
- 通过
label参数给每条折线命名,最后调用legend()生成图例,matplotlib会自动分配不同颜色 - 单图使用
plt.show(block=False),避免程序卡在单图窗口,保证后续合并图能正常生成
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

