将次要 y 轴刻度与主要 x 轴上的带状图对齐 [英] Align secondary y-axis ticks with stripplot on primary x-axis
问题描述
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);
我想在次要y轴上生成一些标签,这些标签与主要y轴上的带状图的y轴刻度线对齐.我希望E与D,F与C处于同一高度,等等.
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.
推荐答案
使用以下命令已正确设置刻度线ax2.set(yticks=ax.get_yticks(), yticklabels=labels2)
.缺少的是轴的限制.这对于两个轴都必须相同.
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.
您可以使用
ax2.set_ylim(ax.get_ylim())
或与 .set
一起使用:
ax2.set(yticks=ax.get_yticks(), yticklabels=labels2, ylim=ax.get_ylim())
完整示例:
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()
这篇关于将次要 y 轴刻度与主要 x 轴上的带状图对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!