数字が 1000 から 20 000 までのデータのリストがあります。
data = [1000, 1000, 5000, 3000, 4000, 16000, 2000]
関数を使用してヒストグラムをプロットするとhist()
、y 軸はビン内の値の発生回数を表します。発生回数の代わりに、発生率を表示したいと思います。
上記のプロットのコード:
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 軸上の 1 つの指定された値に対応していると思います。この値を要素の合計数で割る必要がありますが、どうやら関数に渡すことができないようです...
編集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
他の答えは、まったく複雑に思えます。絶対量ではなく割合を示すヒストグラムは、データに ( はデータポイントの数)で重み付けすることで簡単に作成でき1/n
ますn
。
そして、PercentFormatter
割合 (例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 つの値のうち 3 つが最初のビンにあることがわかります。つまり、3/7 = 43% です。