0
votes

I am looping through a list containing 6 col_names. I loop by taking 3 cols at a time so i can print 3 subplots per iteration later. I have 2 dataframes with same column names so they look identical except for the histograms of each column name.

I want to plot similar column names of both dataframes on the same subplot. Right now, im plotting their histograms on 2 separate subplots.

currently, for col 'A','B','C' in df_plot:

enter image description here

and for col 'A','B','C' in df_plot2: enter image description here

I only want 3 charts where i can combine similar column names into same chart so there is blue and yellow bars in the same chart.

Adding df_plot2 below doesnt work. i think im not defining my second axs properly but im not sure how to do that.

col_name_list = ['A','B','C','D','E','F']
chunk_list = [col_name_list[i:i + 3] for i in xrange(0, len(col_name_list), 3)]
    for k,g in enumerate(chunk_list):
        df_plot = df[g]
        df_plot2 = df[g][df[g] != 0]

        fig, axs = plt.subplots(1,len(g),figsize = (50,20))
        axs = axs.ravel()

        for j,x in enumerate(g):
            df_plot[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs[j], position=0, title = x, fontsize = 30)
            # adding this doesnt work.
            df_plot2[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs[j], position=1, fontsize = 30)
                axs[j].title.set_size(40)
        fig.tight_layout()   
1

1 Answers

0
votes

the solution is to plot on the same ax:

change axs[j] to axs

for k,g in enumerate(chunk_list):
    df_plot = df[g]
    df_plot2 = df[g][df[g] != 0]

    fig, axs = plt.subplots(1,len(g),figsize = (50,20))
    axs = axs.ravel()

    for j,x in enumerate(g):
        df_plot[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs, position=0, title = x, fontsize = 30)
        # adding this doesnt work.
        df_plot2[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs, position=1, fontsize = 30)
            axs[j].title.set_size(40)
    fig.tight_layout() 

then just call plt.plot()

Example this will plot x and y on the same subplot:

import matplotlib.pyplot as plt
x = np.arange(0, 10, 1)
y = np.arange(0, 20, 2)

ax = plt.subplot(1,1)
fig = plt.figure()
ax = fig.gca()
ax.plot(x)
ax.plot(y)

plt.show()

EDIT:

There is now a squeeze keyword argument. This makes sure the result is always a 2D numpy array.

fig, ax2d = subplots(2, 2, squeeze=False)

if needed Turning that into a 1D array is easy:

axli = ax1d.flatten()