2

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?

yeppi
  • 187
  • 1
  • 8
  • 2
    Aren't they shared by default? Provide data with [How to provide a reproducible copy of your DataFrame using `df.head(30).to_clipboard(sep=',')`](https://stackoverflow.com/q/52413246/7758804), then **[edit] your question**, and paste the clipboard into a code block. – Trenton McKinney May 04 '22 at 20:47
  • No, they are not shared in my facetgrid graph. Please see my updated code. As you can see above in the image, they have different y-axis limit. – yeppi May 04 '22 at 20:54
  • If your question is answered now, you might consider marking the answer as accepted. If not, you might clarify what's still unclear. Don't forget to add reproducible test-data to your post. – JohanC May 06 '22 at 18:18

1 Answers1

1

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

JohanC
  • 71,591
  • 8
  • 33
  • 66