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

Matplotlib:如何在单个画布中为多组数据绘制独立直方图子图

嘿,这个问题我之前也踩过坑!直接多次调用plt.hist()确实会把所有直方图叠加在同一个画布的默认子图里,要实现每组数据对应独立子图的需求,Matplotlib有两种非常实用的方式,我给你一步步讲清楚:

方法1:用plt.subplot()逐个创建子图

plt.subplot()的参数格式是plt.subplot(行数, 列数, 当前子图的位置序号),你可以先规划好子图的布局(比如7天的数据可以用2行4列,或者1行7列,看你喜好),然后逐个为每一天的数据创建子图并绘制直方图。

举个例子,假设你已经有了七天的价格数据:

import matplotlib.pyplot as plt
import numpy as np

# 模拟七天的价格数据(你可以替换成自己的mon["price"]等数据)
price_data = {
    "mon": {"price": np.random.normal(50, 10, 100)},
    "tues": {"price": np.random.normal(55, 12, 100)},
    "wed": {"price": np.random.normal(48, 9, 100)},
    "thurs": {"price": np.random.normal(52, 11, 100)},
    "fri": {"price": np.random.normal(58, 13, 100)},
    "sat": {"price": np.random.normal(60, 15, 100)},
    "sun": {"price": np.random.normal(45, 8, 100)}
}

# 规划布局:2行4列的子图(刚好放下7个,最后一个空着也没关系)
days = list(price_data.keys())
for i, day in enumerate(days, start=1):
    # 创建当前子图
    plt.subplot(2, 4, i)
    # 绘制该天价格的直方图
    plt.hist(price_data[day]["price"], bins=15, alpha=0.7, color="#636EFA")
    # 设置子图标题
    plt.title(f"{day.capitalize()} Prices")
    # 设置坐标轴标签
    plt.xlabel("Price")
    plt.ylabel("Count")

# 调整子图间距,避免标题和标签重叠
plt.tight_layout()
plt.show()
方法2:用plt.subplots()一次性创建所有子图

这种方法更高效,它会直接返回画布对象和子图数组,你可以通过遍历数组来为每个子图绘制数据,代码更简洁:

import matplotlib.pyplot as plt
import numpy as np

# 同样先模拟数据(替换成你的真实数据即可)
price_data = {
    "mon": {"price": np.random.normal(50, 10, 100)},
    "tues": {"price": np.random.normal(55, 12, 100)},
    "wed": {"price": np.random.normal(48, 9, 100)},
    "thurs": {"price": np.random.normal(52, 11, 100)},
    "fri": {"price": np.random.normal(58, 13, 100)},
    "sat": {"price": np.random.normal(60, 15, 100)},
    "sun": {"price": np.random.normal(45, 8, 100)}
}

# 创建2行4列的子图,fig是画布,axes是子图数组
fig, axes = plt.subplots(nrows=2, ncols=4, figsize=(12, 6))
days = list(price_data.keys())

# 遍历子图和对应的日期数据
for ax, day in zip(axes.flatten(), days):
    ax.hist(price_data[day]["price"], bins=15, alpha=0.7, color="#EF553B")
    ax.set_title(f"{day.capitalize()} Prices")
    ax.set_xlabel("Price")
    ax.set_ylabel("Count")

# 隐藏最后一个空的子图(可选)
axes.flatten()[-1].axis('off')

# 自动调整布局
plt.tight_layout()
plt.show()

两种方法都能实现你的需求,个人更推荐第二种,代码更整洁,也更容易维护。如果你的数据量不是7组,只需要调整nrows和ncols的数值就行,比如3组数据可以用1行3列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:20:25