8

matplotlib を使用して単純なヒストグラムをプロットしようとしています。たとえば、(実際にはさまざまな距離関数を使用します)

import matplotlib.pyplot as plt
import numpy as np
import itertools


def hamdist(str1, str2):
    """Count the # of differences between equal length strings str1 and str2"""
    if (len(str1) != len(str2)):
        print str1, str2, "Length mismatch bozo!!!!!!"
    diffs = 0
    for ch1, ch2 in itertools.izip(str1, str2):
        if ch1 != ch2:
            diffs += 1
    return diffs

n = 10
bins=np.arange(0,n+2,1)
hamdists = []
for str1 in itertools.product('01', repeat = n):
    for str2 in itertools.product('01', repeat = n):
        hamdists.append(hamdist(str1, str2))
plt.hist(hamdists, bins=bins)
plt.show()

このようなヒストグラムが得られます。

ヒストグラム

次のことを行うにはどうすればよいですか?

  1. 最後のバーが x = 10 の数をカウントするように x 軸を変更します。単純にbins=np.arange(0,11,1)これに変更すると、x = 10 の値が切り捨てられます。
  2. x 軸のすべての点にラベルを付ける
  3. X 軸のラベルを移動して、現在のようにバーの開始位置ではなく、バーの中央の下に配置します。
4

1 に答える 1

20

1 番目と 3 番目のポイントは、ヒストグラム関数の align キーワードを設定することで解決できます (デフォルトはビンの中心である 'mid' です)。2 番目は xticks を手動で設定します。

見る:

fig, ax = plt.subplots(1,1)

ax.hist(hamdists, bins=bins, align='left')
ax.set_xticks(bins[:-1])

ここに画像の説明を入力

于 2013-05-02T08:26:14.890 に答える