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

如何使用matplotlib制作这类多测量值图表?

用Matplotlib高效绘制多组对比图表

你要做的这类带标记点+连线的多组对比图(部分可能包含误差棒),完全不需要手动逐条定义线条,借助结构化数据(比如pandas DataFrame)+循环就能快速实现,代码可复用性还高。

核心实现思路

把所有分组数据整理成结构化格式,然后遍历数据的每个分组,自动绘制对应线条,样式可以批量配置,新增分组时只需更新数据,不用改绘图代码。

示例代码

1. 准备结构化数据

用pandas整理数据(也可以用numpy数组,pandas更方便处理多组数据):

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# 模拟示例中的多组对比数据,x轴为连续变量,列是不同分组
x = np.arange(1, 6)
df = pd.DataFrame({
    '组1': [3.2, 4.1, 5.0, 4.8, 5.5],
    '组2': [2.8, 3.5, 4.2, 4.0, 4.7],
    '组3': [4.0, 4.5, 5.2, 5.8, 6.0]
})

2. 批量绘制折线+标记

遍历DataFrame的列,自动生成每条线,还能统一控制样式:

plt.figure(figsize=(8, 5))

# 预定义不同分组的样式,方便区分
line_styles = ['o-', 's--', '^:']
colors = ['#1f77b4', '#ff7f0e', '#2ca02c']

for i, (group_name, y_values) in enumerate(df.items()):
    plt.plot(x, y_values, line_styles[i], color=colors[i], label=group_name, linewidth=2, markersize=7)

# 补充图表元素
plt.xlabel('X轴变量')
plt.ylabel('Y轴数值')
plt.title('多组对比图表')
plt.legend()
plt.grid(alpha=0.3)
plt.show()

3. 带误差棒的版本(如果示例图包含误差线)

如果你的数据有误差范围,同样可以批量绘制误差棒:

# 模拟每组数据的误差范围
error_df = pd.DataFrame({
    '组1': [0.2, 0.3, 0.25, 0.3, 0.2],
    '组2': [0.15, 0.2, 0.2, 0.25, 0.18],
    '组3': [0.22, 0.25, 0.3, 0.28, 0.2]
})

plt.figure(figsize=(8, 5))
for i, (group_name, y_values) in enumerate(df.items()):
    plt.errorbar(x, y_values, yerr=error_df[group_name], fmt=line_styles[i], 
                 color=colors[i], label=group_name, capsize=5)

plt.xlabel('X轴变量')
plt.ylabel('Y轴数值')
plt.title('带误差棒的多组对比图表')
plt.legend()
plt.grid(alpha=0.3)
plt.show()

为什么这方法更简便

  • 不用重复写plt.plot(),新增分组时只需在DataFrame里加列即可,代码零修改
  • 样式集中管理,不用逐个调整每组的线条、标记样式
  • 结合pandas可以直接读取csv/excel中的真实数据,快速完成可视化

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:53:08