'How to make sub sub plots of pandas dataframe for histogram

I have a nicely working function for plotting a dataframe in a grid. However, I need to combine another dataframe with it, and have each cell/category split into two parts, where the top is the first dataframe and the bottom is the second.

# Generate fake data
data = [np.random.randint(0,10,10) for i in range(10) ]
col = [f'P{i}' for i in range(10)]
df = pd.DataFrame(np.array(data), columns=col, index=['A','B','C','D','E','F','G','H','I','J'])

# Plot data to grid
rows = 5
cols = 2
fig, axs = plt.subplots(rows, cols, sharex=True, sharey=True)
plt.ylim([0,10])
df.T.hist(bins=10,alpha=0.3,ax=axs)
plt.tight_layout()

Which creates:

enter image description here

However, now I would like to add another dataframe

# Make another dataframe
data = [np.random.randint(0,10,10) for i in range(10) ]
col = [f'P{i}' for i in range(10)]
df2 = pd.DataFrame(np.array(data), columns=col, index=['A','B','C','D','E','F','G','H','I','J'])

# Combine dataframes
new_df = pd.concat([df,df2], keys=["DF1",'DF2'])

How can I plot this new dataframe so that for each cell (A, B, C, etc.), the first df is on top and the second is below it. It would be like:

df1 A    df1 B
df2 A    df2 B

df1 C    df1 D
df2 C    df2 D


Solution 1:[1]

You are pretty close:

df.index = df.index+'1'
df2.index = df2.index+'2'
new_df = pd.concat([df,df2]).T
cols = [0,1,10,11,2,3,12,13,4,5,14,15,6,7,16,17,8,9,18,19]
new_df = new_df.iloc[:,cols]

fig, axs = plt.subplots(10, 2, sharex=True, sharey=True,figsize = (12,15))
plt.ylim([0,10])
new_df.hist(bins=20,alpha=0.3,ax=axs);

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1