Reputation: 422
Let's say I have two dataframes:
a = pd.DataFrame({"A": [2,3,4,5],
"B": [4,8,9,10],
"C" :[63,21,23,4],
"D": [56,32,12,2]
})
b = pd.DataFrame({"A": [12,13,14,15],
"B": [41,81,91,10],
"C": [3,2,5,6],
"D": [4,2,3,4]
})
I want to be able to plot scatterplots between the variables on each dataframe with the same name. I've come up with the following code:
fig, ax = plt.subplots((round(len(b)/2)),2,figsize=(10,10))
for i, col in enumerate(b.columns):
sns.regplot(x=a[col], y=b[col], ax=ax[i,0])
plt.title(col)
sns.regplot(x=a[col], y=b[col], ax = ax[i,1])
plt.title(col)
plt.tight_layout()
However, this yields the following figure:
What I want is:
I know this will be simple, but I just can't figure out a way of looping for the second ax[i,1]. Many thanks!
Upvotes: 1
Views: 125
Reputation: 62503
ax
is a numpy
array, so it's easier to use .ravel
, which flattens the array and makes it easier to index
ax
, in the OP, is a (2, 2)
array, which .ravel
flattens to (4,)
.fig, ax = plt.subplots((round(len(b)/2)), 2,figsize=(10,10))
v = ax.ravel()
for i, col in enumerate(b.columns):
sns.regplot(x=a[col], y=b[col], ax=v[i])
v[i].set_xlabel(f'{col}_a')
v[i].set_ylabel(f'{col}_b')
v[i].set_title(col)
plt.tight_layout()
Upvotes: 1