Matplotlib直方图(基本问题)

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()

我得到了如下所示的直方图。

histogram

  1. 如何实现以下更改?
    • 将x轴更改为最后一个柱子计算x = 10的数量。如果我只是简单地更改为 bins=np.arange(0,11,1),那么这就削减了x = 10的值。
  2. 为x轴上的每个点进行标注。
  3. 将x轴标签移动到条形的中间而不是现在的开头。
1个回答

20

通过设置直方图函数的对齐关键字(默认为'mid',即箱子中心),可以解决您的第一和第三个问题。第二个问题可以通过手动设置xticks来解决。

参见:

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

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

输入图像描述


当我设置n = 10并使用bins = np.arange(0,n + 1,1)时,x轴标签仍然只到9。为什么会这样?最后...我宁愿不要在直方图中使用实际刻度,因为它们很容易混淆。 - marshall
因为9是最后一个箱子的起始位置。在您的帖子中,您说您只想显示在条形图下方居中的起始位置。实际上,该箱子的范围从9到10。您可以通过捕获hist函数的结果来探索结果: hist、bins、bars = ax.hist() - Rutger Kassies
哦,谢谢。因此,9到10的一端不能包含在bin中。 - marshall

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接