我使用 matplotlib 的 ImageGrid 辅助类创建了一个绘图。代码如下:
from mpl_tookits.axes_grid1 import ImageGrid
from matplotlib.pyplot import *
fig = figure(figsize=(20, 12), dpi=300)
grid = ImageGrid(fig, 111, nrows_ncols=(3, 4), axes_pad=1, aspect=False)
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=[np.linspace(-.005, .005, num=1000), np.linspace(-.005, .005, num=1000)])
gridax.plot(0, 0, 'ro') # origin
show()
我查看了this cookbook page有关如何为整个图形设置单个 x 和 y 标签的信息,但这些方法似乎仅适用于具有标准子图的标准图形。
我还浏览了一些 mpl_toolkits.axes_grid1.axes_divider.LocatableAxes
的方法,但没有什么让我惊讶的。 同上对于 mpl_toolkits.axes_grid1.axes_grid.ImageGrid
中的方法。
有人知道我如何使用 ImageGrid
做到这一点吗?
最佳答案
在 this github pull request我尝试了一种可能的图形宽度 x 和 y 标签的实现(我很高兴我不是唯一一个希望拥有此类功能的人。
此代码回顾了 PR 实现的要点并生成 this figure 。针对今天(2013 年 3 月 18 日)获取的 matplotlib master 进行测试。
from mpl_toolkits.axes_grid1 import ImageGrid
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(20, 12))
grid = ImageGrid(fig, 111, nrows_ncols=(3, 4), axes_pad=1, aspect=False)
#get the extent of the largest box containing all the axes/subplots
extents = np.array([a.get_position().extents for a in grid]) #all axes extents
bigextents = np.empty(4)
bigextents[:2] = extents[:,:2].min(axis=0)
bigextents[2:] = extents[:,2:].max(axis=0)
#text to mimic the x and y label. The text is positioned in the middle
labelpad=0.08 #distance between the external axis and the text
xlab_t = fig.text((bigextents[2]+bigextents[0])/2, bigextents[1]-labelpad, 'x label',
horizontalalignment='center', verticalalignment = 'bottom')
ylab_t = fig.text( bigextents[0]-labelpad, (bigextents[3]+bigextents[1])/2, 'y label',
rotation='vertical', horizontalalignment = 'left', verticalalignment = 'center')
如果您交互工作或想要封装在函数/类中,您可以在绘制新标签之前使用 [xy]lab_t.set_visible(False)
删除旧标签(有一个text.remove()
方法但尚未实现)。
使用这种方法有一些注意事项:
不适用于
plt.tight_layout
:这是因为该方法特定于subplots
而不是matplotlib.Figure
对象几个月前,有一个想法/PR 在使用
bbox_inches='tight'
保存图形时包含所有艺术家
,但我没有了解此状态。
关于python - 如何为使用 ImageGrid 创建的整个图形创建单轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15466893/