matplotlib 中的直方图未按预期工作

Histogram in matplotlib not working as intended

我有两个数组:

import numpy as np
import pylab as pl

x = np.array([-36., -34.95522388, -33.91044776, -32.86567164,
   -31.82089552, -30.7761194 , -29.73134328, -28.68656716,
   -27.64179104, -26.59701493, -25.55223881, -24.50746269,
   -23.46268657, -22.41791045, -21.37313433, -20.32835821,
   -19.28358209, -18.23880597, -17.19402985, -16.14925373,
   -15.10447761, -14.05970149, -13.01492537, -11.97014925,
   -10.92537313,  -9.88059701,  -8.8358209 ,  -7.79104478,
    -6.74626866,  -5.70149254,  -4.65671642,  -3.6119403 ,
    -2.56716418,  -1.52238806,  -0.47761194,   0.56716418,
     1.6119403 ,   2.65671642,   3.70149254,   4.74626866,
     5.79104478,   6.8358209 ,   7.88059701,   8.92537313,
     9.97014925,  11.01492537,  12.05970149,  13.10447761,
    14.14925373,  15.19402985,  16.23880597,  17.28358209,
    18.32835821,  19.37313433,  20.41791045,  21.46268657,
    22.50746269,  23.55223881,  24.59701493,  25.64179104,
    26.68656716,  27.73134328,  28.7761194 ,  29.82089552,
    30.86567164,  31.91044776,  32.95522388,  34.        ])

y = np.array([ 28,  25,  30,  20,  32,  20,  10,  20,   9,  18,  10,   7,   7,
    14,  10,  11,   4,   8,   7,  11,   3,   7,   3,   1,   4,   3,
     1,   5,   1,   4,   1,   1,   1,  55,   2,   6,   2,   2,   5,
     5,   5,  10,  10,  17,  26,  28,  30,  34, 103, 137,  84,  59,
    55,  69,  59,  70,  72,  75,  66,  90,  79,  74,  62,  80,  59,
    62,  36,  43])

xy 大小相同。现在我想绘制直方图,其中 x 代表 x 轴,y 代表 y 轴。我尝试以下代码:

pl.hist(y,x)

生成的图像是这张:

在此图中,最大值上升到 7,这没有意义,因为在 y 数组中有高达 137 的值。x 数组似乎有效,但我无法弄清楚我的 y 数组有什么问题。

我在这里遵循这个例子:

Plot two histograms at the same time with matplotlib

您使用了错误的功能。您应该像 http://matplotlib.org/examples/api/barchart_demo.html

那样使用 pl.bar()

hist() 所做的是对向量中的数据进行计数,然后绘制这些计数的条形图。例如,如果你有 x=[1 1 3 2 5 5 5 2],那么 hist(x) 将给出一个条形图,高度 2 在位置 1,高度 2 在位置 2,高度 1 在位置 3,高度 0 在位置 4 和高度 3在位置 5.

可以这么说,您的数据已经 "binned"。 plt.hist 获取未合并的数据,将其合并并绘制直方图。你只需要 plt.bar:

>>> plt.bar(x, y)

给出: