4
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
labels1 = ['A','B','C','D']
labels2 = ['E','F','G','H']

fig, ax = plt.subplots()
df = pd.DataFrame(np.random.random(size=(10,4)), columns=('A','B','C','D'))
sns.stripplot(data=df, orient='h', ax=ax)
ax2 = ax.twinx()
ax2.set(yticks=ax.get_yticks(), yticklabels=labels2);

Link to chart produced

I would like to produce some labels on a secondary y-axis that line up with the y-axis ticks of a stripplot on the primary y-axis. I would like E to be at the same height as D, F with C, etc.

I have tried some different methods to align the ticks but having no luck.

Any other suggestions for how to add these labels helpfully accepted.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
ac24
  • 5,325
  • 1
  • 16
  • 31

1 Answers1

2

The ticks are already set correctly using ax2.set(yticks=ax.get_yticks(), yticklabels=labels2). What is missing is the limits of the axes. This has to be the same for both axes.

You can either use

ax2.set_ylim(ax.get_ylim())

or go along with .set:

ax2.set(yticks=ax.get_yticks(), yticklabels=labels2, ylim=ax.get_ylim())

Complete example:

import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

labels1 = ['A','B','C','D']
labels2 = ['E','F','G','H']

fig, ax = plt.subplots()
df = pd.DataFrame(np.random.random(size=(10,4)), columns=('A','B','C','D'))
sns.stripplot(data=df, orient='h', ax=ax)
ax2 = ax.twinx()
ax2.set(yticks=ax.get_yticks(), yticklabels=labels2, ylim=ax.get_ylim())

plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Clear solution, so simple when you put it like this. If there are any efficient alternatives that don't involve creating a secondary axis just for the ticks, I would still be happy to hear them. – ac24 Oct 08 '17 at 21:03
  • While there is the option to label the ticks on the right hand side of an axes, they would always be the same as those on the left. So putting A,B,C,D on both sides, would be easy, but since they should be different here, a different axes needs to be used, like you did here. – ImportanceOfBeingErnest Oct 08 '17 at 21:13
  • I remember I once made a [feature request](https://github.com/matplotlib/matplotlib/issues/8181) about using the second label independently of the first, but it is still open. – ImportanceOfBeingErnest Oct 09 '17 at 09:14