Python 在循环seaborn图中共享次y轴
我试图在循环中的同一行中绘制几个具有次y轴的绘图。我希望他们在第一个图的左侧只有一个主y轴,在最后一个图的右侧只有一个次y轴。到目前为止,我通过shary=子地块的True属性成功地完成了第一件事,但是我在次轴方面遇到了问题Python 在循环seaborn图中共享次y轴,python,matplotlib,seaborn,Python,Matplotlib,Seaborn,我试图在循环中的同一行中绘制几个具有次y轴的绘图。我希望他们在第一个图的左侧只有一个主y轴,在最后一个图的右侧只有一个次y轴。到目前为止,我通过shary=子地块的True属性成功地完成了第一件事,但是我在次轴方面遇到了问题 for r in df.Category1.sort_values().unique(): dfx = df[df['Category1'] == r] fig, axes = plt.subplots(1,3, figsize = (14,6), shar
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轴,我希望它在所有图上都保持一致,在最右侧的图上只显示一次。一个简单的技巧是通过关闭第一个点的点来保持最右侧轴上的点标记标签和点标记第二个子地块。这可以使用索引
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()
df.Category1.sort_values().unique()中的r的:
dfx=df[df['Category1']==r]
图,轴=plt.子批次(1,3,figsize=(14,6),sharey=真)
i=0#根据对一个类似问题的回答,您可以使用轴的get\u shared\u y\u 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))