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

lha*_*ahn 0 python matplotlib histogram

我有两个数组:

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])
Run Code Online (Sandbox Code Playgroud)

双方xy具有相同的尺寸.现在我想绘制直方图,其中x表示x轴和yy轴.我尝试以下代码:

pl.hist(y,x)
Run Code Online (Sandbox Code Playgroud)

生成的图像是这样的:

在此输入图像描述

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

我在这里关注这个例子:

使用matplotlib同时绘制两个直方图

jme*_*jme 7

你的数据已被"分箱",可以这么说.plt.hist获取未绑定的数据,对其进行分类,并绘制直方图.你只需要plt.bar:

>>> plt.bar(x, y)
Run Code Online (Sandbox Code Playgroud)

这使:

在此输入图像描述


hon*_*oni 6

您使用的是错误的功能.您应该使用pl.bar(),如http://matplotlib.org/examples/api/barchart_demo.html

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