在循环的seaborn图中共享次要y轴

5

我正在尝试在循环中在同一行绘制几个带有次要y轴的图。我希望它们只有一个主要y轴位于第一个图的左侧,只有一个次要y轴位于最后一个图的右侧。到目前为止,我通过子图的sharey = True属性成功实现了第一件事,但是我在次要轴方面遇到了麻烦。

for r in df.Category1.sort_values().unique():
    dfx = df[df['Category1'] == r]
    fig, axes = plt.subplots(1,3, figsize = (14,6), sharey=True)
    for (n, dfxx), ax in zip(dfx.groupby("Category2"), axes.flat): 
        ax1 = sns.barplot(x = dfxx['Month'], y = dfxx['value1'], hue = dfxx['Category3'], ci = None, palette = palette1, ax=ax)
        ax2 = ax1.twinx()
        ax2 = sns.pointplot(x = dfxx['Month'], y=dfxx['value2'], hue = dfxx['Category3'], ci = None, sort = False, legend = None, palette = palette2) 

plt.tight_layout()
plt.show()

正如您所看到的,在循环的一次迭代中,它只有一个主要的左侧y轴,但是每个图都会出现次要y轴,我希望它对于所有的图表都是一致的,并且仅在最右边的图表中出现一次。

2个回答

2

要得到你想要的结果,一个简单的技巧是只在最右边的轴上保留刻度标签和刻度线,关闭第一个和第二个子图的刻度线。可以使用索引 i 来实现:

for r in df.Category1.sort_values().unique():
    dfx = df[df['Category1'] == r]
    fig, axes = plt.subplots(1,3, figsize = (14,6), sharey=True)
    i = 0 # <--- Initialize a counter
    for (n, dfxx), ax in zip(dfx.groupby("Category2"), axes.flat): 
        ax1 = sns.barplot(x = dfxx['Month'], y = dfxx['value1'], hue = dfxx['Category3'], ci = None, palette = palette1, ax=ax)
        ax2 = ax1.twinx()
        ax2 = sns.pointplot(x = dfxx['Month'], y=dfxx['value2'], hue = dfxx['Category3'], ci = None, sort = False, legend = None, palette = palette2) 
        if i < 2: # <-- Only turn off the ticks for the first two subplots
            ax2.get_yaxis().set_ticks([]) # <-- Hiding the ticks
        i += 1  # <-- Counter for the subplot
plt.tight_layout()

但是要注意的是,你的三个子图在次坐标轴上有不同的y轴限制。因此,在隐藏刻度之前最好使轴限制相等。为此,您可以使用ax2.set_ylim(minimum, maximum),其中minimum和maximum是您想要将轴限制为的值。


2
根据this类似问题的回答,您可以使用轴的get_shared_y_axes()函数以及其join()方法:
fig, axes = plt.subplots(1,3, figsize = (14,6), sharey=True)

secaxes = []                            # list for collecting all secondary y-axes
for i, ax in enumerate(axes):
    ax.plot(range(10))
    secaxes.append(ax.twinx())          # put current secondary y-axis into list
    secaxes[-1].plot(range(10, 0, -1))
secaxes[0].get_shared_y_axes().join(*secaxes) # share all y-axes

for s in secaxes[:-1]:                  # make all secondary y-axes invisible
    s.get_yaxis().set_visible(False)    # except the last one

enter image description here

测试共享缩放:

secaxes[1].plot(range(20, 10, -1))

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接