下面是我用 matplotlib 创建的图形。问题很明显——标签重叠,整个事情是一团乱七八糟的东西。
我尝试为每个子图调用 tight_layout
,但这会使我的 ipython-notebook 内核崩溃。
如何修复布局?可接受的方法包括固定每个子图的 xlabel、ylabel 和标题,但另一种(也许更好)方法是为整个图使用单个 xlabel、ylabel 和标题。
这是我用来生成上述子图的循环:
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()
最佳答案
您需要 ImageGrid
( tutorial )。
第一个示例直接从该链接提取(并稍作修改):
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()
关于python - 如何处理这些子图中的重叠标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15441646/