使用Matplotlib归一化直方图:将Bins值设为观测占比
用Matplotlib绘制纵轴为观测值百分比的直方图
我来帮你完善这个示例,实现纵轴代表总观测值百分比的直方图。首先得处理你的二维数据,同时调整直方图的计算逻辑,让每个bin的高度对应观测值占总数的百分比。这里有两种常用的实现方式:
方法1:使用weights参数直接计算百分比
这种方法通过给每个数据点赋予权重,直接让直方图的高度显示百分比:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import matplotlib.ticker as tck import seaborn as sns import numpy as np sns.set(style='dark') imagen2 = plt.figure(1, figsize=(5, 2)) imagen2.suptitle('StackOverflow Matplotlib histogram demo') # 生成数据并处理:展平二维数组,调整为从0开始 luminance = np.random.randn(1000, 1000) luminance_flat = luminance.flatten() luminance_flat = luminance_flat - luminance_flat.min() # 确保数据从0开始 # 计算权重:每个数据点的权重为 1/总数量 * 100,这样bin高度就是百分比 weights = np.ones_like(luminance_flat) / len(luminance_flat) * 100 # 绘制直方图 n, bins, patches = plt.hist(luminance_flat, bins=20, weights=weights) # 添加纵轴标签 plt.ylabel('Percentage of total observations') plt.xlabel('Luminance') plt.tight_layout() plt.show()
方法2:使用密度模式转换为百分比
这种方法先绘制概率密度直方图,再将纵轴刻度转换为百分比:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import matplotlib.ticker as tck import seaborn as sns import numpy as np sns.set(style='dark') imagen2 = plt.figure(1, figsize=(5, 2)) imagen2.suptitle('StackOverflow Matplotlib histogram demo') # 生成数据并处理 luminance = np.random.randn(1000, 1000) luminance_flat = luminance.flatten() luminance_flat = luminance_flat - luminance_flat.min() # 绘制密度直方图 n, bins, patches = plt.hist(luminance_flat, bins=20, density=True) # 将纵轴转换为百分比格式 plt.gca().yaxis.set_major_formatter(tck.PercentFormatter(xmax=1)) # 添加标签 plt.ylabel('Percentage of total observations') plt.xlabel('Luminance') plt.tight_layout() plt.show()
关键细节说明
- 首先要把二维的
luminance数组展平为一维,因为plt.hist需要一维输入数据。 - 代码里用
luminance_flat - luminance_flat.min()把数据调整为从0开始,满足你备注里的需求。 - 两种方法的区别:
- 方法1的权重计算更直观,直接对应每个bin的观测占比;
- 方法2的密度模式适合后续需要做概率相关的扩展,再通过刻度转换得到百分比。
内容的提问来源于stack exchange,提问作者amyspark
相关产品推荐
相关产品推荐

