Matplotlib直方图(基本问题)

mar*_*all 6 python matplotlib

我试图用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()
Run Code Online (Sandbox Code Playgroud)

我得到一个看起来像这样的直方图.

直方图

我该怎么做?

  1. 更改x轴,使最后一个条形计算x = 10的数字.如果我只是更改bins=np.arange(0,11,1)为此值,则截断x = 10的值.
  2. 标记x轴中的每个点
  3. 将x轴标签移动到条形图的中间位置,而不是像现在一样位于它们的开头.

Rut*_*ies 16

您可以通过设置直方图函数的align关键字来解决您的第一个和第三个点(默认为"mid",即bin的中心).第二步通过手动设置xticks.

看到:

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

ax.hist(hamdists, bins=bins, align='left')
ax.set_xticks(bins[:-1])
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述