matplotlib直方图库宽度的变化

2024-10-01 00:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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()

Tags: projectdata宽度pltgraphimagesselectiveset
1条回答
网友
1楼 · 发布于 2024-10-01 00:31:27

正如ImportanceOfBeingErnest在注释中指出的,除非您在绘图时特别设置了range参数,否则存储箱将在数据的范围内分布。所以在我的例子中,对于一些线条,范围是0-0.18,在其他地方是0-0.98,因此导致了条形宽度的变化。解决方法是将直方图线修改为:

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

使用range参数,并且rwidth参数是无关的和可选的。在

相关问题 更多 >