【发布时间】:2018-07-23 07:54:08
【问题描述】:
我有一个数据列表,其中的数字在 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))))
我一直在看这个post,它描述了一个使用FuncFormatter 的例子,但我不知道如何让它适应我的问题。欢迎提供一些帮助和指导:)
编辑: FuncFormatter 使用的 to_percent(y, position) 函数的主要问题。我猜 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 的方法
实际期望的输出(带有全局变量的方法):
【问题讨论】:
标签: python matplotlib