我试着在循环的同一行中绘制几个具有次要y轴的曲线图。我希望它们在第一个图的左侧只有一个主y轴,在最后一个图的右侧只有一个次y轴。到目前为止,我成功地完成了第一件事,就是通过subplots的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轴,但次要的出现在每个图上,我希望它对所有的图都是一致的,并且对于最右边的图只出现一次。
发布于 2018-12-18 20:51:24
获得所需内容的一个简单技巧是,通过关闭第一个和第二个子图的刻度,将tick-labels和ticks 保持在最右边的轴上。这可以使用索引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()但你应该注意,你的3个子图在第二轴上有不同的y限制。因此,在隐藏刻度之前,最好使轴限制相等。为此,可以使用ax2.set_ylim(minimum, maximum),其中minimum和maximum是要将轴限制为的值。
发布于 2018-12-18 20:53:07
根据this对类似问题的回答,您可以将axes的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

共享伸缩测试:
secaxes[1].plot(range(20, 10, -1))

https://stackoverflow.com/questions/53831482
复制相似问题