我该如何处理这些子图中的重叠标签?

5 投票
1 回答
1581 浏览
提问于 2025-04-17 19:16

下面是我用matplotlib创建的一个图。问题很明显——标签重叠了,整个图看起来乱七八糟,根本无法阅读。

在这里输入图片描述

我试着对每个子图调用了 tight_layout,但这导致我的ipython-notebook内核崩溃。

我该怎么做才能修复这个布局呢?可以考虑的办法包括为每个子图单独设置x轴标签、y轴标签和标题,但还有一种(也许更好的)方法是为整个图设置一个统一的x轴标签、y轴标签和标题。

这是我用来生成上面这些子图的循环代码:

for i, sub in enumerate(datalist):
    subnum = i + start_with
    subplot(3, 4, i)

     # format data (sub is a PANDAS dataframe)
    xdat = sub['x'][(sub['in_trl'] == True) & (sub['x'].notnull()) & (sub['y'].notnull())]
    ydat = sub['y'][(sub['in_trl'] == True) & (sub['x'].notnull()) & (sub['y'].notnull())]

    # plot
    hist2d(xdat, ydat, bins=1000)
    plot(0, 0, 'ro')  # origin

    title('Subject {0} in-Trial Gaze'.format(subnum))
    xlabel('Horizontal Offset (degrees visual angle)')
    ylabel('Vertical Offset (degrees visual angle)')

    xlim([-.005, .005])
    ylim([-.005, .005])
    # tight_layout  # crashes ipython-notebook kernel

show()

更新:

好的,看来 ImageGrid 是个不错的选择,但我的图还是看起来有点奇怪:

在这里输入图片描述

这是我使用的代码:

fig = figure(dpi=300)
grid = ImageGrid(fig, 111, nrows_ncols=(3, 4), axes_pad=0.1)

for gridax, (i, sub) in zip(grid, enumerate(eyelink_data)):
    subnum = i + start_with

     # format data
    xdat = sub['x'][(sub['in_trl'] == True) & (sub['x'].notnull()) & (sub['y'].notnull())]
    ydat = sub['y'][(sub['in_trl'] == True) & (sub['x'].notnull()) & (sub['y'].notnull())]

    # plot
    gridax.hist2d(xdat, ydat, bins=1000)
    plot(0, 0, 'ro')  # origin

    title('Subject {0} in-Trial Gaze'.format(subnum))
    xlabel('Horizontal Offset\n(degrees visual angle)')
    ylabel('Vertical Offset\n(degrees visual angle)')

    xlim([-.005, .005])
    ylim([-.005, .005])

show()

1 个回答

3

你想要使用 ImageGrid (可以参考这个教程)。

下面这个例子是直接从那个链接上拿来的(稍微做了一些修改):

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np

im = np.arange(100)
im.shape = 10, 10

fig = plt.figure(1, (4., 4.))
grid = ImageGrid(fig, 111, # similar to subplot(111)
                nrows_ncols = (2, 2), # creates 2x2 grid of axes
                axes_pad=0.1, # pad between axes in inch.
                aspect=False, # do not force aspect='equal'
                )

for i in range(4):
    grid[i].imshow(im) # The AxesGrid object work as a list of axes.

plt.show()

撰写回答