繁体   English   中英

如何使用 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轴,并删除不需要的刻度标签。

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

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()

在 sns.FacetGrid 中共享 twinx 轴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM