Matplotlib subplots_adjust hspace所以标题和xlabels不重叠?

时间:2010-03-10 15:32:03

标签: python matplotlib

比如说matplotlib中的3行子图,一行的xlabels可以与下一行的标题重叠。一个人必须摆弄pl.subplots_adjust(hspace),这很烦人。

是否有hspace的配方可以防止重叠并适用于任何nrow?

""" matplotlib xlabels overlap titles ? """
import sys
import numpy as np
import pylab as pl

nrow = 3
hspace = .4  # of plot height, titles and xlabels both fall within this ??
exec "\n".join( sys.argv[1:] )  # nrow= ...

y = np.arange(10)
pl.subplots_adjust( hspace=hspace )

for jrow in range( 1, nrow+1 ):
    pl.subplot( nrow, 1, jrow )
    pl.plot( y**jrow )
    pl.title( 5 * ("title %d " % jrow) )
    pl.xlabel( 5 * ("xlabel %d " % jrow) )

pl.show()

我的版本:

  • matplotlib 0.99.1.1,
  • Python 2.6.4,
  • Mac OSX 10.4.11,
  • 后端:Qt4AggTkAgg => Tkinter回调中的异常)

(对于许多额外的观点,任何人都可以概述matplotlib的包装工​​/垫片如何工作,沿着Tcl / Tk书中第17章“打包者”的路线?)

3 个答案:

答案 0 :(得分:43)

您可以使用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

答案 1 :(得分:34)

Jose发布的链接已经更新,pylab现在有一个tight_layout()函数可以自动执行此操作(在matplotlib版本1.1.0中)。

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout

http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout

答案 2 :(得分:18)

我觉得这很棘手,但有一些信息here at the MatPlotLib FAQ。它相当麻烦,需要找出个别元素(ticklabels)占用的空间......

<强>更新 该页面指出tight_layout()函数是最简单的方法,它会尝试自动纠正间距。

否则,它会显示获取各种元素(例如标签)大小的方法,以便您可以更正轴元素的间距/位置。以下是上述FAQ页面中的示例,该页面确定了非常宽的y轴标签的宽度,并相应地调整了轴宽度:

import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.set_yticks((2,5,7))
labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))

def on_draw(event):
   bboxes = []
   for label in labels:
       bbox = label.get_window_extent()
       # the figure transform goes from relative coords->pixels and we
       # want the inverse of that
       bboxi = bbox.inverse_transformed(fig.transFigure)
       bboxes.append(bboxi)

   # this is the bbox that bounds all the bboxes, again in relative
   # figure coords
   bbox = mtransforms.Bbox.union(bboxes)
   if fig.subplotpars.left < bbox.width:
       # we need to move it over
       fig.subplots_adjust(left=1.1*bbox.width) # pad a little
       fig.canvas.draw()
   return False

fig.canvas.mpl_connect('draw_event', on_draw)

plt.show()