python - Python pyplot.hist:如何将每个条形图的总和为 1?
问题描述
我目前的堆叠直方图编码如下:
x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]
pyplot.hist(x_multi, 10, histtype='barstacked')
但是,我想将每个堆叠条缩放到 1 的高度,以便 y 轴现在描绘每个系列条表示的 bin 的百分比(即每个堆叠条的百分比)。像这样的东西:
但是,此图像来自网络上使用硬编码类别的不同示例(如 x 轴所示)。这可以使用 pyplot.hist 来完成,自动保留正确的分箱和 x 轴吗?
解决方案
显然,没有一个简单的解决方案。最快的方法是使用 matplotlib 的hist
函数计算直方图,然后对其进行归一化,然后使用 bar 命令重新绘制它。我现在将其推广到任意数量的堆叠单元。它还计算垃圾箱的真实中心,而不仅仅是边缘。
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
d = np.random.randn(300).reshape(3,100)
def percentage_bar_stack(data, bins=10):
'''Creates a stacked histogram bar chart using data and a given amount of bins'''
data_binned, edge_bins, patches = plt.hist(data.T, bins=bins, stacked=True, width=.5)
plt.title('stacked bar chart, raw')
real_bins = [(edge_bins[i]+edge_bins[i+1])/2 for i in range(bins)]
data_binned = np.array(data_binned)
data_binned /= data_binned.sum(0)
plt.figure()
print(data_binned)
for i in range(len(data_binned)):
plt.bar(real_bins, data_binned[i], bottom=data_binned[:i].sum(0), width=.5)
plt.title('normalized to percentage')
percentage_bar_stack(d)
推荐阅读
- python - Python Pandas 根据多列条件替换值
- django - manage.py runserver 比我的 gunicorn/nginx conf 具有更好的性能是否正常?
- python - 检查一个数据框中的值是否存在于另一个数据框中并创建列
- html - CSS位置绝对停止旋转属性
- bash - 了解 bash 的“test -z”与“test -n”
- python - MLflow 将运行保存到特定的实验 ID
- phpmyadmin - 但是在我更改表并添加约束后没有 DELIMITER 存在错误
- bash - 如何使用对话框 --checklist 显示文本文件的全部内容
- reactjs - 在所有路线上显示 Nav 组件
- linux - 当用户和组不存在时如何创建它们