使用matplotlib中的许多子块改进子块大小/间距

2024-04-25 18:13:21 发布

您现在位置:Python中文网/ 问答频道 /正文

this question非常相似,但不同的是,我的数字可以大到需要的程度。

我需要在matplotlib中生成一大堆垂直叠加的图。结果将使用figsave保存并在网页上查看,因此我不在乎最终图像有多高,只要子块是间隔的,这样它们就不会重叠。

不管我允许这个数字有多大,子块似乎总是重叠的。

我的代码当前看起来像

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)

Tags: importmatplotlibmyfigplt数字somethis
3条回答

尝试使用^{}

举个简单的例子:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)
fig.tight_layout() # Or equivalently,  "plt.tight_layout()"

plt.show()

没有紧凑的布局

enter image description here


布局紧凑 enter image description here

可以使用plt.subplots_adjust更改子块(source)之间的间距

呼叫签名:

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文件控制

我发现subblots_adjust(hspace=0.001)最终对我有效。当我使用space=None时,每个图之间仍有空白。然而,将其设置为非常接近零的值似乎会迫使它们排队。我在这里上传的不是最优雅的代码,但是你可以看到hspace是如何工作的。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tic

fig = plt.figure()

x = np.arange(100)
y = 3.*np.sin(x*2.*np.pi/100.)

for i in range(5):
    temp = 510 + i
    ax = plt.subplot(temp)
    plt.plot(x,y)
    plt.subplots_adjust(hspace = .001)
    temp = tic.MaxNLocator(3)
    ax.yaxis.set_major_locator(temp)
    ax.set_xticklabels(())
    ax.title.set_visible(False)

plt.show()

enter image description here

相关问题 更多 >