【问题标题】:Python and plotting the histograms (using matplotlib)Python 和绘制直方图(使用 matplotlib)
【发布时间】:2019-11-29 22:09:08
【问题描述】:

我的一般问题:我有一个函数,可以创建和保存直方图。在我的代码中,我运行该函数两次:第一次使用一个数据数组创建和保存一个图,第二次使用另一个数据数组创建和保存第二个图。 程序完成后,我得到 2 个 .png 文件:第一个包含一个数据数组的直方图,第二个包含第一个和第二个数据数组的直方图! 我需要的是一个数组的一个图,另一个数组的第二个图。我的脑子要炸了,我就是想不通,这是怎么回事。有人可以给我一个线索吗?

这是我的部分代码和生成的图像:

    def mode(station_name, *args):
        ...
        #before here the 'temp' data array is generated

        temp_counts = {}

        for t in temp:
            if t not in temp_counts:
                temp_counts[t] = 1
            else:
                temp_counts[t] += 1

        print(temp_counts)  **#this dictionary has DIFFERENT content being printed in two function runs**

        x = []
        for k, v in temp_counts.items():
            x += [k for _ in range(v)]

        plt.hist(x, bins="auto")

        plt.grid(True)

        plt.savefig('{}.png'.format(station_name))

    #---------------------------------------------------------------------------------------------------
    mode(station_name, [...])
    mode(station_name, [...])

the 'like' of 1 image i get

the 'like' of 2 image i get

real images i get after my full script finishes #1

real images i get after my full script finishes #2

【问题讨论】:

标签: python matplotlib plot


【解决方案1】:

如果您使用plt.plotsomething..,则该图将添加到当前正在使用的图形中,因此第二个直方图将添加到第一个直方图。我建议使用 matplotlib 对象 API 来避免混淆:您创建图形和轴,然后从它们开始生成绘图。这是你的代码:

def mode(station_name, *args):
    ...
    #before here the 'temp' data array is generated

    temp_counts = {}

    for t in temp:
        if t not in temp_counts:
            temp_counts[t] = 1
        else:
            temp_counts[t] += 1

    print(temp_counts)  **#this dictionary has DIFFERENT content being printed in two function runs**

    x = []
    for k, v in temp_counts.items():
        x += [k for _ in range(v)]

    fig, ax = plt.subplots(1):
    ax.hist(x, bins="auto")
    ax.grid(True)
    fig.savefig('{}.png'.format(station_name))

#---------------------------------------------------------------------------------------------------
mode(station_name, [...])
mode(station_name, [...])

这应该为您完成这项工作

【讨论】:

  • 非常感谢,这解决了我的问题。另外,我发现,保存后与 plt.close('all') 一起使用的关闭数字可以完成这项工作。