如果我在matplotlib图中添加一个副标题,它就会被子图的标题所覆盖。有没有人知道如何轻松解决这个问题?我尝试过tight_layout()
函数,但它只会让事情变得更糟。
示例:
import numpy as np
import matplotlib.pyplot as plt
f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure()
fig.suptitle('Long Suptitle', fontsize=24)
plt.subplot(121)
plt.plot(f)
plt.title('Very Long Title 1', fontsize=20)
plt.subplot(122)
plt.plot(g)
plt.title('Very Long Title 2', fontsize=20)
plt.tight_layout()
plt.show()
发布于 2011-11-24 04:16:56
您可以使用plt.subplots_adjust(top=0.85)
手动调整间距
import numpy as np
import matplotlib.pyplot as plt
f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure()
fig.suptitle('Long Suptitle', fontsize=24)
plt.subplot(121)
plt.plot(f)
plt.title('Very Long Title 1', fontsize=20)
plt.subplot(122)
plt.plot(g)
plt.title('Very Long Title 2', fontsize=20)
plt.subplots_adjust(top=0.85)
plt.show()
发布于 2015-02-10 00:42:39
另一种简单易用的解决方案是使用suptitle调用中的y参数来调整图中的suptitle文本的坐标(参见docs):
import numpy as np
import matplotlib.pyplot as plt
f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure()
fig.suptitle('Long Suptitle', y=1.05, fontsize=24)
plt.subplot(121)
plt.plot(f)
plt.title('Very Long Title 1', fontsize=20)
plt.subplot(122)
plt.plot(g)
plt.title('Very Long Title 2', fontsize=20)
plt.show()
发布于 2019-07-09 18:37:44
紧凑的布局不适用于suptitle,但constrained_layout
可以。请参阅此问题Improve subplot size/spacing with many subplots in matplotlib
我发现立即添加子情节看起来更好,即
fig, axs = plt.subplots(rows, cols, constrained_layout=True)
# then iterating over the axes to fill in the plots
但也可以在创建图形时添加该图形:
fig = plt.figure(constrained_layout=True)
ax1 = fig.add_subplot(cols, rows, 1)
# etc
注意:为了使我的子图更紧密,我还使用了
fig.subplots_adjust(wspace=0.05)
而constrained_layout不能处理以下内容:(
https://stackoverflow.com/questions/8248467
复制相似问题