matplotlib画堆叠、并列直方图

在用 matplotlib.pyplot.hist 画分布图时,若总分布由几个分量组成(如高斯混合),想用不同颜色标识出来,方便看到各分量占比,参考 [1]。

效果:

  • 分布由两个分量(x、y)组成;
  • 左上:总分布;
  • 右上:总分布,y 轴用 log scale;
  • 左下:并列展示两个分量分布;
  • 右下:总分布,但堆叠展示两个分量分布,用不同颜色标识。

histogram

Code

  • hist 传多个数组(tuple/list),label、color 也是相应的顺序;
  • stacked=True 是堆叠,False 是并列。
import numpy as np
import matplotlib.pyplot as plt

# 示例分布,分 x、y 两分量,且数量不同(10000 和 20000)
x = np.random.randn(10000) # 正太分布
y = np.random.uniform(low=x.min(), high=x.max(), size=[20000]) # 均匀分布
z = np.concatenate((x, y)) # 总分布

cmap = plt.get_cmap('viridis')

fig, ax = plt.subplots(2, 2, figsize=(15, 15))
# 左上。似乎排在前面的数组会画先,从而出现在底部
ax[0][0].hist(z, bins=100, label="x and y", color=cmap(0.25))
# 右上。y 轴用 log scale
ax[0][1].hist(z, bins=100, label="x and y", color=cmap(0.25), log=True)
# 左下,并列
ax[1][0].hist((x, y), bins=100, label=("x", "y"))
# 右下,堆叠
ax[1][1].hist((x, y), bins=100, label=("x", "y"), stacked=True)

# 图例
for i in range(len(ax)):
    for j in range(len(ax[0])):
        ax[i][j].legend(fancybox=True, framealpha=0) # 透明图例

plt.tight_layout()
fig.savefig("test.png", bbox_inches='tight')
plt.close(fig)

References

  1. The histogram (hist) function with multiple data sets
  2. matplotlib.pyplot.hist
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值