首页 > 解决方案 > 绘制 y 轴为百分比的直方图(使用 FuncFormatter?)

问题描述

我有一个数据列表,其中数字在 1000 到 20 000 之间。

data = [1000, 1000, 5000, 3000, 4000, 16000, 2000]

当我使用该函数绘制直方图时hist(),y 轴表示 bin 中值的出现次数。而不是出现的次数,我想知道出现的百分比。

上面数据列表的直方图

上图的代码:

f, ax = plt.subplots(1, 1, figsize=(10,5))
ax.hist(data, bins = len(list(set(data))))

我一直在看这篇文章,它描述了一个使用示例,FuncFormatter但我不知道如何使它适应我的问题。欢迎提供一些帮助和指导:)

编辑:to_percent(y, position) . 使用的函数的主要问题FuncFormatter。我猜 y 对应于 y 轴上的一个给定值。我需要将此值除以显然无法传递给函数的元素总数...

编辑 2:由于使用了全局变量,我不喜欢当前的解决方案:

def to_percent(y, position):
    # Ignore the passed in position. This has the effect of scaling the default
    # tick locations.
    global n

    s = str(round(100 * y / n, 3))
    print (y)

    # The percent symbol needs escaping in latex
    if matplotlib.rcParams['text.usetex'] is True:
        return s + r'$\%$'
    else:
        return s + '%'

def plotting_hist(folder, output):
    global n

    data = list()
    # Do stuff to create data from folder

    n = len(data)
    f, ax = plt.subplots(1, 1, figsize=(10,5))
    ax.hist(data, bins = len(list(set(data))), rwidth = 1)

    formatter = FuncFormatter(to_percent)
    plt.gca().yaxis.set_major_formatter(formatter)

    plt.savefig("{}.png".format(output), dpi=500)

编辑3:方法与density = True

在此处输入图像描述

实际期望的输出(使用全局变量的方法):

在此处输入图像描述

标签: pythonmatplotlib

解决方案


其他答案似乎非常复杂。可以通过使用 对数据进行加权来轻松生成显示比例而不是绝对数量的直方图1/n,其中n是数据点的数量。

然后PercentFormatter可以使用 a 将比例(例如0.45)显示为百分比(45%)。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter

data = [1000, 1000, 5000, 3000, 4000, 16000, 2000]

plt.hist(data, weights=np.ones(len(data)) / len(data))

plt.gca().yaxis.set_major_formatter(PercentFormatter(1))
plt.show()

在此处输入图像描述

在这里,我们看到 7 个值中的三个在第一个 bin 中,即 3/7=43%。


推荐阅读