Outlaw
Outlaw

Reputation: 359

Python and plotting the histograms (using matplotlib)

My problem in general: I have a function, that creates and saves the histograms. In my code I run the function twice: 1st time to create and save one plot with one data array, 2nd time to create and save second plot with another data array. After the completion of the program, I get 2 .png files: the 1st one contains the histogram of one data array, the 2nd one contains histogram of the first AND the second data arrays! What I need is one plot for one array, and second plot for another array. My mind's gonna blow, I just can't get, what's wrong here. Might somebody give me a clue?

Here's a part of my code and resulting images:

    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

Upvotes: 2

Views: 98

Answers (1)

Andrea
Andrea

Reputation: 3077

If you use plt.plotsomething.. the plot is added to the current figure in use, therefore the second histogram is added to the first. I suggest using the matplotlib object API to avoid confusion: you create figure and axis and you generate your plots starting from them. Here's your code:

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, [...])

This should do the job for you

Upvotes: 1

Related Questions