0
votes

I have 2 pandas dataframes that are the same length with the same column names. I'd like to loop through and plot the columns against one another - column1 in df1 against col1 in df2. I'd like bar graphs

df1:

   A  B  C
1  0  4  8
2  5  6  9
3  2  5  1

df2:

   A  B  C
1  9  4  5
2  1  4  2
3  5  5  1
2
What is the issue, exactly? Please see How to Ask, help center. - AMC

2 Answers

0
votes

Maybe something like below, not very sure what you mean by a bar plot with one against the other, I plotted side by side for every now

df1=pd.DataFrame({'A':[0,5,2],'B':[4,6,5],'C':[8,9,1]})
df2=pd.DataFrame({'A':[9,1,5],'B':[4,4,5],'C':[5,2,1]})

fig,ax = plt.subplots(1,3,figsize=(8,5))
x1 = [i-0.1 for i in range(len(df1))]
x2 = [i+0.1 for i in range(len(df2))]
for i,col in enumerate(df1.columns):
    ax[i].bar(x=x1,height=df1[col],width=0.2,label="df1")
    ax[i].bar(x=x2,height=df2[col],width=0.2,label="df2")
    ax[i].legend()

enter image description here

0
votes

It is called a grouped bar chart/clustered bar chart/multi-series bar chart

If I got the gist of what you are saying here is the easiest way to what you want.

Creating the data frames you mentioned:

df1 = pd.DataFrame(np.array([[0, 4, 8], [5, 6, 9], [2, 5, 1]]), columns=['a', 'b', 'c'])
df2 = pd.DataFrame(np.array([[9, 4, 5], [1, 4, 2], [5, 5, 1]]), columns=['a', 'b', 'c'])

Stacking them on top of each other (if the index isn't important use ignore_index=True option in append method):

combined = df1.append(df2)

Since you want to plot the columns you need them as rows first because, by default, DataFrame.plot plots with the rows as the X-axis.

To get them as rows we transpose as follows and that's it.

combined.transpose().plot(kind='bar')

or

combined.T.plot(kind='bar')

Here is the plot: Cluster bar chart