如何迭代绘制到正确的子图轴
How to iteratively plot to the correct subplot axes
假设我有两个数据帧:
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]
})
我希望能够在具有相同名称的每个数据帧上的变量之间绘制散点图。我想出了以下代码:
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()
然而,这会产生下图:
我想要的是:
我知道这很简单,但我就是想不出第二个 ax[i,1] 的循环方式。
非常感谢!
ax
是一个numpy
数组,所以用.ravel
比较简单,把数组压扁了,更容易索引
ax
,在 OP 中,是一个 (2, 2)
数组,.ravel
扁平化为 (4,)
。
- 有关子图轴数组的更多详细信息,请参阅以下 SO 问题:
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()
假设我有两个数据帧:
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]
})
我希望能够在具有相同名称的每个数据帧上的变量之间绘制散点图。我想出了以下代码:
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()
然而,这会产生下图:
我想要的是:
我知道这很简单,但我就是想不出第二个 ax[i,1] 的循环方式。 非常感谢!
ax
是一个numpy
数组,所以用.ravel
比较简单,把数组压扁了,更容易索引ax
,在 OP 中,是一个(2, 2)
数组,.ravel
扁平化为(4,)
。
- 有关子图轴数组的更多详细信息,请参阅以下 SO 问题:
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()