python - 绘制 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
实际期望的输出(使用全局变量的方法):
解决方案
其他答案似乎非常复杂。可以通过使用 对数据进行加权来轻松生成显示比例而不是绝对数量的直方图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%。
推荐阅读
- r - 拆分由点连接的两个单词
- c# - C# 项目。试图在 .txt 文件中查找平均数、最小数、最大数和数字数
- python - 在使用 Pandas 的 Python 中,是否可以逐块读取 4B 行并针对内存中已经存在的 30M 行数据帧过滤每个卡盘?
- node.js - 谷歌云节点应用无法连接跨域请求被阻止
- html-email - 在 HTML 电子邮件签名上托管自定义字体
- javascript - 制作一个每 1 秒更改一次图像的滑块
- azure-devops - 使用 ASP.NET yaml 模板的新 Azure DevOps 管道失败
- c# - DataGrid 单行复选框正在选择所有行
- vba - 如何使用 VBA 将文本框中输入的值分配给另一个表单 MS Access 上的组合框选择
- python - 在 pycharm 中将 python dict 结构视为字典