add-semi-colons
add-semi-colons

Reputation: 18800

matplotlib custom plotting multiple columns in dataframe

I have a pandas DataFrame with multiple columns that I would like to plot histogram for each of the column I want to have a separate histogram and have all the histograms in one row after plot is completed.

Here is my attempt:

fig, ax = plt.subplots(nrows=1, ncols=4, figsize=(20,5))

n_cols = ['a', 'b', 'c', 'd']
colors = ['#800000','#3C91E6','#59C9A5','#9BE564']
counter = 0

for j in range(4):
    n, bins, patches = plt.hist(df[n_cols[counter]], 
                                bins=50, 
                                facecolor = '#2ab0ff', 
                                edgecolor='#169acf', 
                                linewidth=0.5, ax=ax[j])
    n = n.astype('int') # it MUST be integer#
    for i in range(len(patches)):
        patches[i].set_facecolor(plt.cm.viridis(n[i]/max(n)))
    # Make one bin stand out   
    patches[47].set_fc('red') # Set color
    patches[47].set_alpha(1) # Set opacity        
    counter+=1

    fig.suptitle('distributions', fontsize=18)

I get a inner() got multiple values for argument ax

But a single plot works well without any issue. Which is the section in side the loop:

Upvotes: 1

Views: 100

Answers (1)

tdy
tdy

Reputation: 41327

Matplotlib's plot() doesn't take an ax param like pandas/seaborn. Matplotlib uses ax[j].plot() instead of plt.plot(ax=ax[j]):

n, bins, patches = ax[j].hist(df[n_cols[counter]], 
                            bins=50, 
                            facecolor = '#2ab0ff', 
                            edgecolor='#169acf', 
                            linewidth=0.5)

Upvotes: 2

Related Questions