Bla*_*ski 5 python matplotlib seaborn
我正在尝试在循环的同一行中绘制一些带有辅助 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()
Run Code Online (Sandbox Code Playgroud)
因此,正如您所看到的循环的一次迭代,它在左侧只有一个主 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()
Run Code Online (Sandbox Code Playgroud)
但您应该小心,您的 3 个子图在次轴上具有不同的 y 限制。因此,在隐藏刻度之前,最好使轴限制相等。为此,您可以使用ax2.set_ylim(minimum, maximum)最小值和最大值,其中最小值和最大值是您希望轴限制的值。
| 归档时间: |
|
| 查看次数: |
3799 次 |
| 最近记录: |