python - Matplotlib 外轴破坏子图布局
问题描述
我想绘制一个带有 3 个子图的图形。中间的有 3 个不同的 x 轴,其中一个被分离并放置在子图下方。当我Gridspec
用于布局时,绘图区域等距分布,但不同子图的轴标签之间的填充有很大不同:
这是重现该图的代码:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(3.375, 6.5))
gs0 = gridspec.GridSpec(3, 1, figure=fig)
ax0 = fig.add_subplot(gs0[0])
ax0.set_xlabel('x label 0')
ax1 = fig.add_subplot(gs0[1])
ax1.set_xlabel('x label 1a')
secax1 = ax1.twiny()
secax1.xaxis.set_ticks_position('bottom')
secax1.xaxis.set_label_position('bottom')
secax1.spines['bottom'].set_position(('outward', 40))
secax1.set_xlabel('x label 1b')
thax1 = ax1.twiny()
thax1.set_xlabel('x label 1c')
ax2 = fig.add_subplot(gs0[2])
ax2.set_xlabel('x label 2a')
ax2.set_ylabel('y label 2')
secax2 = ax2.twiny()
secax2.set_xlabel('x label 2b')
plt.tight_layout()
plt.savefig('3 subplots same size.png', dpi=300)
plt.show()
我正在寻找一种方法来使完整子图之间的间距相等,以及附加轴及其标签等所有内容。或者一种在网格内手动移动子图的方法。子图不需要保持相同的大小。
我试着改变height_ratios
as
gs0 = gridspec.GridSpec(3, 1, figure=fig, height_ratios=[1, 1.5, 1])
但它不会影响地块之间的空间。
解决方案
您可以使用 plt.subplots 并在真实图之间放置不可见的“间隙图”,然后您可以通过更改间隙图的 height_ratio 来调整间隙
f, (ax0, gap1, ax1, gap2, ax2) = plt.subplots(5, 1,figsize=(3.375,8), gridspec_kw={'height_ratios': [1,1,1,1.75,1]})
gap1.axis('off')# Make the gap plots invisable
gap2.axis('off')# Make the gap plots invisable
#ax0 = fig.add_subplot(gs0[0])
ax0.set_xlabel('x label 0')
#ax1 = fig.add_subplot(gs0[2])
ax1.set_xlabel('x label 1a')
secax1 = ax1.twiny()
secax1.xaxis.set_ticks_position('bottom')
secax1.xaxis.set_label_position('bottom')
secax1.spines['bottom'].set_position(('outward', 40))
secax1.set_xlabel('x label 1b')
thax1 = ax1.twiny()
thax1.set_xlabel('x label 1c')
#ax2 = fig.add_subplot(gs0[5])
ax2.set_xlabel('x label 2a')
ax2.set_ylabel('y label 2')
secax2 = ax2.twiny()
secax2.set_xlabel('x label 2b')
输出
推荐阅读
- java - 如何检查哪个子类被传递到构造函数中?
- javascript - PhantomJS 网站需要按键进行身份验证
- reactjs - 带有订阅的 Apollo-Client:失败:WebSocket 握手期间出错:意外的响应代码:400
- c++ - auto 之前的私有类实例
- python - 如何将子目录重定向到运行 python 的 Heroku 应用程序?
- java - 如何从android中的CustomAdapter获取arraylist引用?
- powershell - 如何防止 powershell 将 YabaDabaDoo 视为 Get-YabaDabaDoo 的别名?
- mysql - 如何在单个查询中更新mysql同一列中的不同值?
- reactjs - 如何在 React 中正确使用三元运算符
- c# - Blazor 个人帐户失败并显示“ArgumentException:'value' 中的路径必须以'/'开头。(参数'value')”