2010-03-10 35 views
32

Con, por ejemplo, 3 filas de subparcelas en matplotlib, xlabels de una fila puede superponer el título de la siguiente. Uno tiene que jugar con pl.subplots_adjust(hspace), lo cual es molesto.Subplots Matplotlib_adjust hspace para títulos y xlabels no se superponen?

¿Hay alguna receta para hspace que evite las superposiciones y que funcione para cualquier persona?

""" 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() 

Mis versiones:

  • matplotlib 0.99.1.1,
  • Python 2.6.4,
  • Mac OS X 10.4.11,
  • backend: Qt4Agg (TkAgg => Excepción en Llamada de Tkinter)

(para muchos puntos extra, ¿alguien puede delinear cómo funciona el empacador/espaciador de matplotlib, siguiendo las líneas del capítulo 17 "el empacador" en el libro Tcl/Tk?)

+2

es probable que desee presentar una entrada de bug/deseos para este en el matplotlib bugtracker http://sourceforge.net/tracker/?group_id=80706 –

+2

Ha intentado 'pl. tight_layout() 'before' pl.show() 'para una solución" automática " – Sebastian

+0

@Sebastian Raschka, "UserWarning: tight_layout: regresa al procesador Agg", matplotlib 1.4.3 en un mac. (La pregunta fue hace 5 años.) – denis

Respuesta

16

Encuentro esto bastante complicado, pero hay algo de información en él here at the MatPlotLib FAQ . Es bastante complicado, y requiere averiguar acerca de qué espacio de elementos individuales (ticklabels) ocupan ...

Actualización: Los estados de página que la función tight_layout() es la forma más fácil de ir, que intenta corregir automáticamente espaciado.

De lo contrario, muestra formas de adquirir los tamaños de varios elementos (por ejemplo, etiquetas) para que luego pueda corregir los espaciamientos/posiciones de los elementos de los ejes. Aquí está un ejemplo de la página de preguntas frecuentes anteriormente, que determina la anchura de una etiqueta de eje y muy amplia, y ajusta el ancho de eje en consecuencia:

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() 
+0

aceptar, pero engorroso de hecho - mttiw, más problemas de lo que vale – denis

+0

Enlace se ha ido. Esta respuesta se volvió inútil de hecho. – jojo

+1

El enlace existe nuevamente - dice 'tight_layout()' ahora es el camino a seguir, que de hecho lo es. – Demis

39

Puede utilizar plt.subplots_adjust para cambiar el espaciado entre las subparcelas enlace

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 
+3

La pregunta decía "uno tiene que jugar con pl.subplots_adjust (hspace), molesto". – denis

Cuestiones relacionadas