使用多个子图改善子图大小/间距

13 浏览
0 Comments

使用多个子图改善子图大小/间距

我需要在matplotlib中生成一堆垂直堆叠的图。结果将使用savefig保存,并在网页上查看,因此我不关心最终图像有多高,只要子图间距适当,不会重叠。

无论我允许图形有多大,子图似乎总是重叠。

我的代码当前看起来像

import matplotlib.pyplot as plt
import my_other_module
titles, x_lists, y_lists = my_other_module.get_data()
fig = plt.figure(figsize=(10,60))
for i, y_list in enumerate(y_lists):
    plt.subplot(len(titles), 1, i)
    plt.xlabel("Some X label")
    plt.ylabel("Some Y label")
    plt.title(titles[i])
    plt.plot(x_lists[i],y_list)
fig.savefig('out.png', dpi=100)

admin 更改状态以发布 2023年5月23日
0
0 Comments

你可以使用plt.subplots_adjust改变子图之间的间距。

调用签名:

subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

参数含义(建议默认值)为:

left  = 0.125  # the left side of the subplots of the figure
right = 0.9    # the right side of the subplots of the figure
bottom = 0.1   # the bottom of the subplots of the figure
top = 0.9      # the top of the subplots of the figure
wspace = 0.2   # the amount of width reserved for blank space between subplots
hspace = 0.2   # the amount of height reserved for white space between subplots

实际默认值由rc文件控制。

0
0 Comments

请仔细阅读 Matplotlib:紧凑布局指南 并尝试使用 matplotlib.pyplot.tight_layoutmatplotlib.figure.Figure.tight_layout

以下是一个简单的示例:

import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(8, 8))
fig.tight_layout() # Or equivalently,  "plt.tight_layout()"
plt.show()


没有使用紧凑布局:

enter image description here


使用紧凑布局:

enter image description here

0