Matplotlib直方图

时间:2015-10-25 19:03:43

标签: python matplotlib

我试图绘制一个简单的直方图。我已将数据处理为列表: X = [30,2728,2894,2582,2309,2396,2491,2453,2382,2325,2225,2359,2138 ......]

其中每个位置对应于具有该值的项目数(因此30项为0,2728为1等) 如果我将此列表绘制为条形图,我会得到所需的结果,但分辨率太高(即每个值都是一个桶)。我想要做的是合并桶,这样我可以得到我的X值:0,1-10,10-50,50-150,150-500,并且Y值是所需范围内的项目总和,所以对于0我将得到y值30,对于1-10我将有价值总和(2728,2894,2582,2309,2396,2491,2453,2382,2325,2225)等。

我试过这种方式:

plt.hist(X,bins=[0,1,10])

但是我没有得到理想的结果,我希望得到一个0-1,y = 30,第二个栏1-10,y = 24785,但这不是它的情节

最好的方法是什么?

2 个答案:

答案 0 :(得分:1)

对于预处理数据的方式,绘制它的正确方法是:

X = [30, 2728, 2894, 2582, 2309, 2396, 2491, 2453, 2382, 2325, 2225, 2359, 2138]
plt.bar(range(len(X)),X);

enter image description here

然而,matplotlib为绘制直方图提供了一种更简单,更直接的方式:

x = np.random.randn(1000)
plt.hist(x, bins=30);

enter image description here

如果您希望更直接地控制分箱,可能需要切换到Pandas并尝试pd.cut,您可以在其中定义自己的分档:

import pandas as pd
df = pd.DataFrame({'x':np.random.randint(0,100,1000)})
factor = pd.cut(df.x, [1,10,20,100])
df.groupby(factor).apply(lambda x: x.count()).plot(kind='bar', rot=45, legend=0);

enter image description here

答案 1 :(得分:0)

您想将存储桶合并到自定义列表中: 0,1-10,10-50,50-150,150-500。 由于这是一个自定义列表,我不确定您是否可以直接告诉plt.hist这些垃圾箱是什么。我建议手动计算每个自定义箱中有多少个值。如果您使用X将列表np.array()转换为NumPy数组,则会非常有用。

    X = np.array([30, 2728, 2894, 2582, 2309, 2396, 2491, 2453, 2382, 2325, 2225, 2359, 2138])
    ##Customized bin list:
    bin_list = np.array( [0,1,10,50,150, 500, np.inf ])   ##Can specify 500 to be inf as well
    plot_bin = np.zeros( len(bin_list)-1)
    for bin_n in range(len(bin_list)-1):
       plot_bin[bin_n] = np.sum( (X >= bin_list[bin_n]) & (X < bin_list[bin_n+1]) )

    ## Create string version of the buckets to use as labels
    str_bin_list_lower = [str(a) for a in bin_list[0: -1 ]]
    x_ticks = np.arange(len(bin_list)-1)-0.35
    plt.bar( x_ticks, plot_bin)
    plt.xticks( x_ticks+0.35, str_bin_list_lower )
编辑:我误解了你的问题。你有一个[0,10,50]的bin列表,想要添加[0],[1-10],[10-50]等数字。你应该更熟悉Python索引元素的方式。例如,range(10)[0:5] = [0,1,2,3,4]range(10)[5:10] = [5,6,7,8,9]。在制作bin列表时需要考虑到这一点。 然后分箱过程应该是:

    X = np.array([30, 2728, 2894, 2582, 2309, 2396, 2491, 2453, 2382, 2325, 2225, 2359, 2138])
    bin_list = np.array( [0,10,50,150, 500, np.inf ])+1   ##Can specify 500 
    plot_bin = np.zeros( len(bin_list)-1)
    for bin_n in range(len(bin_list)-1):
      if bin_n==len(bin_list)-2:
        plot_bin[bin_n] = np.sum( X[ bin_list[bin_n]: ] )
      else:
        plot_bin[bin_n] = np.sum( X[ bin_list[bin_n]:bin_list[bin_n+1]+1] )
    plot_bin = np.insert(plot_bin, 0, X[0])