matplotlib直方图箱宽度的变化

时间:2018-06-14 17:26:01

标签: python matplotlib histogram

我在matplotlib中创建一个直方图,并且遇到问题,因为当它们都应该是相同的宽度时,条的宽度会发生变化。这方面的一个例子是:

Histogram showing variable bar width between iterations

在图像中,左列具有完整的直方图,右列以完整直方图的部分放大。在完整的直方图中,由于某些未知原因,两个试验之间的条宽度不同,其中在缩放的右侧,它们具有相同的尺寸条。我希望它们具有相同的大小条,其中rwidth = 1并且相邻的区间之间没有间隙。

当我将rwidth保持为默认值并且将其设置为等于1时,都会发生这种情况。类似的问题被问到here,但它似乎与变化的刻度范围或条形轮廓有关重叠,两者都不适用于我的图表。

有谁知道为什么我的垃圾箱宽度不同,或者我还能尝试让它们保持相同的宽度?

我正在使用的代码如下所示:

def graph_pvalues(both, selective, clearcut, trials, location):
    # define overall figure
    plt.figure(figsize=(16, int(project_images*(trials*0.15 + 0.5))))
    gs = gridspec.GridSpec(project_images-1, 3) 

    # plot one graph per substack size
    for v in range(project_images-1):
        # define subsets of data being graphed, remove nan values, and combine
        S_sub = selective[:, v]
        C_sub = clearcut[:, v]
        B_sub = both[:, v]
        graphed_data = [B_sub[~np.isnan(B_sub)], S_sub[~np.isnan(S_sub)], C_sub[~np.isnan(C_sub)]]

        # plot main graph
        ax1 = plt.subplot2grid((project_images-1, 3), (v, 0), colspan=2)
        ax1.hist(graphed_data, bins=50, rwidth=1, label=['both', 'selective', 'clearcut'])
        ax1.axis([0, 1, 0, trials])
        ax1.set_title("Disturbance at the %s using a substack of %i images" % (location, v+1))
        ax1.set_xlabel("p-value")
        ax1.set_ylabel("Number of trials")
        ax1.legend(prop={'size': 10})

        # plot zoom graph for 0 to 0.1
        ax2 = plt.subplot2grid((project_images-1, 3), (v, 2))
        ax2.hist(graphed_data, bins=10, range=(0, 0.1), label=['both', 'selective', 'clearcut'])
        ax2.axis([0, 0.1, 0, trials])
        ax2.set_title("Zoom 0 - 0.1 (%s, %i images)" % (location, v+1))
        ax2.set_xlabel("p-value")
        ax2.legend(prop={'size': 10})

    plt.tight_layout()

    plt.show()

1 个答案:

答案 0 :(得分:0)

正如ImportanceOfBeingErnest在评论中所指出的那样,除非您在绘图时专门设置范围参数,否则这些区域将分布在您的数据范围内。所以在我的情况下,对于某些线条,范围是0-0.18,在其他地方0-0.98,因此导致条宽度的变化。解决方案是将直方图线修改为:

ax1.hist(graphed_data, bins=50, range=(0,1), label=['both', 'selective', 'clearcut'])

使用range参数,并且rwidth参数不相关且可选。

相关问题