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

如何在Python中绘制以月份为X轴、数据为Y轴的箱线图?

实现类似Matlab boxchart 的箱线图(Python)

方法1:使用Seaborn(推荐,代码更简洁)

Seaborn的boxplot可以直接按分类变量(月份)分组绘制箱线图,无需手动分组,和Matlab的boxchart逻辑完全匹配。

代码示例

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# 替换为你的真实数据
date_month = np.array([1, 1, 2, 2, 2, 3, 3, 3, 3])
delta_gmb_gris = np.array([0.5, 0.7, 0.3, 0.6, 0.4, 0.8, 1.0, 0.9, 0.7])

# 绘制箱线图
plt.figure(figsize=(10,6))
sns.boxplot(x=date_month, y=delta_gmb_gris)

# 设置图表标签与标题
plt.xlabel('月份')
plt.ylabel('delta_gmb_gris')
plt.title('各月份delta_gmb_gris分布箱线图')

plt.show()

如果date_month是字符串类型(如['Jan', 'Feb', 'Mar']),代码无需修改,Seaborn会自动识别分类维度。


方法2:纯Matplotlib实现

若不想依赖Seaborn,需先手动按月份分组整理数据,再传入boxplot函数。

代码示例

import numpy as np
import matplotlib.pyplot as plt

# 替换为你的真实数据
date_month = np.array([1, 1, 2, 2, 2, 3, 3, 3, 3])
delta_gmb_gris = np.array([0.5, 0.7, 0.3, 0.6, 0.4, 0.8, 1.0, 0.9, 0.7])

# 按月份分组:提取唯一月份,收集对应数值
unique_months = np.unique(date_month)
grouped_data = [delta_gmb_gris[date_month == month] for month in unique_months]

# 绘制箱线图
plt.figure(figsize=(10,6))
plt.boxplot(grouped_data)

# 将X轴刻度设置为对应月份
plt.xticks(range(1, len(unique_months)+1), unique_months)

# 设置图表标签与标题
plt.xlabel('月份')
plt.ylabel('delta_gmb_gris')
plt.title('各月份delta_gmb_gris分布箱线图')

plt.show()

关键说明

Matplotlib原生boxplot要求传入按分组整理的二维数据(每个子列表对应一个月份的所有数值),这和Matlab直接传入两个一维数组的逻辑不同——这也是很多人用Matplotlib时结果不符合预期的核心原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 21:12:19