gpt4 book ai didi

python - matplotlib tight_layout + gridspec + fig.suptitle 看起来很糟糕

转载 作者:太空宇宙 更新时间:2023-11-04 02:11:30 27 4
gpt4 key购买 nike

我有一个使用 Matplotlib 2.2.2 的非常漂亮的 GridSpec 图,但我无法为整个图制作一个漂亮的标题。示例:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
%matplotlib inline

def example(tl):
fig = plt.figure(figsize=(14,8))
hr = [3,3,3,1,1]
wr = [3,1]
ny = len(hr)
nx = len(wr)
gs = gridspec.GridSpec(ny,nx,
height_ratios=hr,
width_ratios=wr,
hspace=0.08, wspace=0.1)
for j in xrange(nx):
ax = [fig.add_subplot(gs[0,j])]
ax += [fig.add_subplot(gs[i,j], sharex=ax[0]) for i in xrange(1,ny)]
for axi in ax:
axi.plot([0,1,2],[0,1,4])
fig.suptitle('The quick brown fox jumps over the lazy dog.')
if tl:
gs.tight_layout(fig)

如果我运行 example(False) 没有紧凑的布局,我会在数字上方获得大量空间:

enter image description here

如果我运行 example(True) 以获得紧凑的布局,我会得到负空间:

enter image description here

我怎样才能解决这个问题,并从子图中获得具有适当边距的图形级标题?

最佳答案

tight_layout() 不考虑图形级别的艺术家。

使用约束布局

但是,有一个相对较新的替代方案,称为 constrained_layout .使用这个,图形标题将被包括在内。请注意,要使其正常工作,您需要通过它的 figure 参数将图形提供给 GridSpec

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

def example(tl):
fig = plt.figure(figsize=(14,8), constrained_layout=tl)
hr = [3,3,3,1,1]
wr = [3,1]
ny = len(hr)
nx = len(wr)
gs = gridspec.GridSpec(ny,nx, figure=fig,
height_ratios=hr,
width_ratios=wr,
hspace=0.08, wspace=0.1)
for j in range(nx):
ax = [fig.add_subplot(gs[0,j])]
ax += [fig.add_subplot(gs[i,j], sharex=ax[0]) for i in range(1,ny)]
for axi in ax:
axi.plot([0,1,2],[0,1,4])
fig.suptitle('The quick brown fox jumps over the lazy dog.')


example(True)
plt.show()

enter image description here

更新上边距

或者,您可以调用tight_layout 后更新上边距。例如。作为

gs.update(top=0.95)

代码:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

def example(tl):
fig = plt.figure(figsize=(14,8))
hr = [3,3,3,1,1]
wr = [3,1]
ny = len(hr)
nx = len(wr)
gs = gridspec.GridSpec(ny,nx, figure=fig,
height_ratios=hr,
width_ratios=wr,
hspace=0.08, wspace=0.1)
for j in range(nx):
ax = [fig.add_subplot(gs[0,j])]
ax += [fig.add_subplot(gs[i,j], sharex=ax[0]) for i in range(1,ny)]
for axi in ax:
axi.plot([0,1,2],[0,1,4])
fig.suptitle('The quick brown fox jumps over the lazy dog.')
if tl:
gs.tight_layout(fig)
gs.update(top=0.95)


example(True)
plt.show()

enter image description here

关于python - matplotlib tight_layout + gridspec + fig.suptitle 看起来很糟糕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53642083/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com