我试图调整suptitle
高于多面板的数字,我很难搞清楚如何调整figsize
并随后定位suptitle。
问题是调用plt.suptitle("my title", y=...)
来调整suptitle的位置也会调整图形尺寸。几个问题:
suptitle(..., y=1.1)
在哪里实际上把标题?据我所知,suptitle的y
参数的文档指向matplotlib.text.Text,但我不知道当你有多个子图时,数字坐标是什么意思。y
指定为suptitle
时,对图形尺寸的影响是什么?subplots_adjust
?),为每个面板添加一个图形标题,为整个图形添加一个suptitle,保持图中每个轴的大小?一个例子:
data = np.random.random(size=100)
f, a = plt.subplots(2, 2, figsize=(10, 5))
a[0,0].plot(data)
a[0,0].set_title("this is a really long title\n"*2)
a[0,1].plot(data)
a[1,1].plot(data)
plt.suptitle("a big long suptitle that runs into the title\n"*2, y=1.05);
显然我每次制作一个数字都可以调整,但我需要一个通常无需人工干预的解决方案。我尝试了约束布局和紧凑的布局;对任何复杂的数字都不可靠。
1.数字坐标是什么意思?
图坐标为0到1,其中(0,0)是左下角,(1,1)是右上角。因此,y=1.05
的坐标稍微超出了数字。
2.指定y到suptitle时对图形大小的影响是什么?
将y
指定为suptitle对数字大小没有任何影响。
3A。如何手动调整图形大小和间距,为每个面板添加一个图形标题,为整个图形添加一个图形?
首先,不会添加额外的换行符。即如果你想要2行,请不要使用3个换行符(\n
)。然后可以根据需要调整子图参数,为标题留出空间。例如。 fig.subplots_adjust(top=0.8)
并使用y <= 1
将标题置于图中。
import matplotlib.pyplot as plt
import numpy as np
data = np.random.random(size=100)
fig, axes = plt.subplots(2, 2, figsize=(10, 5))
fig.subplots_adjust(top=0.8)
axes[0,0].plot(data)
axes[0,0].set_title("\n".join(["this is a really long title"]*2))
axes[0,1].plot(data)
axes[1,1].plot(data)
fig.suptitle("\n".join(["a big long suptitle that runs into the title"]*2), y=0.98)
plt.show()
3B。 ...同时保持图中每个斧头的大小?
维持轴的大小并且仍然有足够的空间用于标题只能通过改变整体图形大小来实现。
这可能如下所示,我们定义了一个函数make_space_above
,它以轴的数组作为输入,以及以英寸为单位的新期望的上边距。例如,您得出的结论是,您需要1英寸的边距来托管您的标题:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.random(size=100)
fig, axes = plt.subplots(2, 2, figsize=(10, 5), squeeze = False)
axes[0,0].plot(data)
axes[0,0].set_title("\n".join(["this is a really long title"]*2))
axes[0,1].plot(data)
axes[1,1].plot(data)
fig.suptitle("\n".join(["a big long suptitle that runs into the title"]*2), y=0.98)
def make_space_above(axes, topmargin=1):
""" increase figure size to make topmargin (in inches) space for
titles, without changing the axes sizes"""
fig = axes.flatten()[0].figure
s = fig.subplotpars
w, h = fig.get_size_inches()
figh = h - (1-s.top)*h + topmargin
fig.subplots_adjust(bottom=s.bottom*h/figh, top=1-topmargin/figh)
fig.set_figheight(figh)
make_space_above(axes, topmargin=1)
plt.show()
(左:未调用make_space_above
;右:调用make_space_above(axes, topmargin=1)
)
...或使用constrained_layout:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.random(size=100)
f, a = plt.subplots(2, 2, figsize=(10, 5), constrained_layout=True)
a[0,0].plot(data)
a[0,0].set_title("this is a really long title\n"*2)
a[0,1].plot(data)
a[1,1].plot(data)
plt.suptitle("a big long suptitle that runs into the title\n"*2);