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

如何循环生成12个月度密度图对比2017、2018年的变量分布

问题原因
  • 最初的代码仅做了月份遍历,没有嵌套年份遍历逻辑,无法在同一张子图中绘制两个年份的密度曲线
  • plt.subplots(4,3)返回的是二维数组,直接和月份列表zip会报错,需要先展平为一维数组
  • 后续尝试kdeplot时参数配置错误:同时传入x="Year"和y="Variable"会生成双变量联合密度图,不是你需要的单变量分布曲线;且自行创建子图后再传col参数会产生逻辑冲突,导致输出异常。
  • distplot在新版seaborn中已经弃用,建议用kdeplot替代实现单变量密度曲线绘制。
可直接运行的实现代码
import matplotlib.pyplot as plt
import seaborn as sns

years = [2017, 2018]
months = range(1,13)

# 创建画布与子图,将4行3列的二维子图数组展平为一维方便遍历
fig = plt.figure(figsize=(15, 12), constrained_layout=True)
axs = fig.subplots(4, 3).flatten()

for ax, month in zip(axs, months):
    ax.set_title(f"Month = {month}")
    # 嵌套遍历两个年份,在同一张子图中分别绘制密度曲线
    for year in years:
        # 筛选对应月份、对应年份的数据集
        subset = df[(df["Month"] == month) & (df["Year"] == year)]
        sns.kdeplot(
            data = subset,
            x = "Variable",
            linewidth = 3,
            label = str(year),
            ax = ax
        )
    ax.legend() # 显示当前子图的年份图例
    ax.set_xlabel("变量值")
    ax.set_ylabel("密度")

plt.show()
简化实现方案(seaborn分面绘图)

如果不想写嵌套循环,也可以直接用seaborn的分面绘图功能,无需手动管理子图:

import seaborn as sns

sns.displot(
    data = df,
    x = "Variable",
    hue = "Year", # 按年份区分曲线颜色
    kind = "kde", # 指定绘制单变量密度曲线
    col = "Month", # 按月份拆分为多个子图
    col_wrap = 3, # 每行展示3个子图
    linewidth = 3,
    height = 2.5
)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 18:00:00