如何使用 seaborn 共享 facetgrid x 和 y 轴

How to share facetgrid x and y axis using seaborn

运行 下面的代码生成 seaborn facetgrid 图。

merged1=merged[merged['TEST'].isin(['VL'])]
merged2=merged[merged['TEST'].isin(['CD4'])]

g = sns.relplot(data=merged1, x='Days Post-ART', y='Log of VL and CD4', col='PATIENT ID',col_wrap=4, kind="line", height=4, aspect=1.5,
                color='b',  facet_kws={'sharey':True,'sharex':True})

for patid, ax in g.axes_dict.items():  # axes_dict is new in seaborn 0.11.2
    ax1 = ax.twinx()
    sns.lineplot(data=merged2[merged2['PATIENT ID'] == patid], x='Days Post-ART', y='Log of VL and CD4', color='r')

我已经使用 facet_kws={'sharey':True, 'sharex':True} 共享 x 轴和 y 轴,但它无法正常工作。有人可以帮忙吗?

如评论中所述,默认情况下共享 FacetGrid 轴。但是,twinx 轴不是。此外,对 twinx 的调用似乎重置了 y 刻度标签的默认隐藏。

您可以手动共享 twinx 轴,并删除不需要的刻度标签。

下面是一些使用鸢尾花数据集的示例代码:

from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np

iris = sns.load_dataset('iris')

g = sns.relplot(data=iris, x='petal_length', y='petal_width', col='species', col_wrap=2, kind="line",
                height=4, aspect=1.5, color='b')

last_axes = np.append(g.axes.flat[g._col_wrap - 1::g._col_wrap], g.axes.flat[-1])
shared_right_y = None
for species, ax in g.axes_dict.items():
     ax1 = ax.twinx()
     if shared_right_y is None:
          shared_right_y = ax1
     else:
          shared_right_y.get_shared_y_axes().join(shared_right_y, ax1)
     sns.lineplot(data=iris[iris['species'] == species], x='petal_length', y='sepal_length', color='r', ax=ax1)
     if not ax in last_axes:  # remove tick labels from secondary axis
          ax1.yaxis.set_tick_params(labelleft=False, labelright=False)
          ax1.set_ylabel('')
     if not ax in g._left_axes:  # remove tick labels from primary axis
          ax.yaxis.set_tick_params(labelleft=False, labelright=False)

plt.tight_layout()
plt.show()