如何使用xarray GroupBy绘制分组箱线图
按分组绘制xarray DataSet的箱线图解决方案
步骤说明
- 导入所需依赖库
- 对DataSet按指定字段分组并转换为适合绘图的格式
- 绘制并列箱线图并配置轴标签与样式
代码实现
import xarray as xr import matplotlib.pyplot as plt import seaborn as sns # 加载你的xarray DataSet(替换为实际数据加载方式) ds = xr.load_dataset("your_dataset.nc") # 按'init_area_rounded'分组,提取'g10'变量并转为pandas DataFrame # 转换后便于绘图库直接处理 grouped_df = ds["g10"].groupby("init_area_rounded").to_dataframe().reset_index() # 可选:移除含缺失值的行(若数据存在空值) grouped_df = grouped_df.dropna(subset=["g10"]) # 配置绘图风格 sns.set_style("whitegrid") # 创建画布并设置尺寸 plt.figure(figsize=(12, 6)) # 绘制并列箱线图:X轴为分组区域,Y轴为10小时增长量 sns.boxplot(x="init_area_rounded", y="g10", data=grouped_df) # 设置轴标签与标题 plt.xlabel("区域") plt.ylabel("10小时增长量") plt.title("各区域10小时增长量分布箱线图") # 旋转X轴标签避免名称重叠(按需调整角度) plt.xticks(rotation=45) # 自动调整布局,防止标签被截断 plt.tight_layout() # 显示图表 plt.show()
关键细节说明
- 利用xarray的
groupby方法完成分组后,转换为pandas DataFrame是因为主流绘图库(matplotlib/seaborn)对其支持更友好,能直接映射分组字段与数值字段。 - 如果不需要seaborn,也可以用matplotlib原生的
boxplot方法,只需将分组数据整理为列表传入:# 用matplotlib原生方法绘制的替代代码 groups = grouped_df.groupby("init_area_rounded")["g10"].apply(list).values labels = grouped_df["init_area_rounded"].unique() plt.figure(figsize=(12, 6)) plt.boxplot(groups, labels=labels) plt.xlabel("区域") plt.ylabel("10小时增长量") plt.xticks(rotation=45) plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Alyssa S
相关产品推荐
相关产品推荐

