user18708380
user18708380

Reputation:

How to share facetgrid x and y axis using seaborn

enter image description hereRunning this below code produces seaborn facetgrid graphs.

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

I've used the facet_kws={'sharey':True, 'sharex':True} to share the x-axis and y-axis but it's not working properly. Can someone assist?

Upvotes: 2

Views: 815

Answers (1)

JohanC
JohanC

Reputation: 80279

As stated in the comments, the FacetGrid axes are shared by default. However, the twinx axes are not. Also, the call to twinx seems to reset the default hiding of the y tick labels.

You can manually share the twinx axes, and remove the unwanted tick labels.

Here is some example code using the iris dataset:

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

sharing of twinx axes in sns.FacetGrid

Upvotes: 0

Related Questions