GridSpec与Python中的共享轴 [英] GridSpec with shared axes in Python

查看:267
本文介绍了GridSpec与Python中的共享轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

针对另一线程的此解决方案建议使用gridspec.GridSpec而不是plt.subplots.但是,当我在子图之间共享轴时,我通常使用如下语法

This solution to another thread suggests using gridspec.GridSpec instead of plt.subplots. However, when I share axes between subplots, I usually use a syntax like the following

  fig, axes = plt.subplots(N, 1, sharex='col', sharey=True, figsize=(3,18))

使用GridSpec时如何指定sharexsharey?

推荐答案

首先,只要您对略微的精确性感到满意,就可以轻松解决原始问题.只需在调用tight_layout之后将子图的最高范围重置为默认的 :

First off, there's an easier workaround for your original problem, as long as you're okay with being slightly imprecise. Just reset the top extent of the subplots to the default after calling tight_layout:

fig, axes = plt.subplots(ncols=2, sharey=True)
plt.setp(axes, title='Test')
fig.suptitle('An overall title', size=20)

fig.tight_layout()
fig.subplots_adjust(top=0.9) 

plt.show()

但是,要回答您的问题,您需要在较低的级别上创建子图以使用gridspec.如果要像subplots那样复制共享轴的隐藏,则需要使用sharey参数来手动完成. html#matplotlib.figure.Figure.add_subplot> Figure.add_subplot ,并用plt.setp(ax.get_yticklabels(), visible=False)隐藏重复的刻度.

However, to answer your question, you'll need to create the subplots at a slightly lower level to use gridspec. If you want to replicate the hiding of shared axes like subplots does, you'll need to do that manually, by using the sharey argument to Figure.add_subplot and hiding the duplicated ticks with plt.setp(ax.get_yticklabels(), visible=False).

例如:

import matplotlib.pyplot as plt
from matplotlib import gridspec

fig = plt.figure()
gs = gridspec.GridSpec(1,2)
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1], sharey=ax1)
plt.setp(ax2.get_yticklabels(), visible=False)

plt.setp([ax1, ax2], title='Test')
fig.suptitle('An overall title', size=20)
gs.tight_layout(fig, rect=[0, 0, 1, 0.97])

plt.show()

这篇关于GridSpec与Python中的共享轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆