2011-06-30 18 views
167

Muy similar a this question pero con la diferencia de que mi figura puede ser tan grande como debe ser.Mejore el tamaño/espaciado de las subtramas con muchas subtramas en matplotlib

Necesito generar un montón de parcelas apiladas verticalmente en matplotlib. El resultado se guardará con figsave y se verá en una página web, por lo que no me importa qué tan alta sea la imagen final, siempre que las subtramas estén espaciadas para que no se superpongan.

No importa cuán grande permita que sea la figura, las subtramas siempre parecen superponerse.

Mi código se ve actualmente como

import matplotlib.pyplot as plt 
import my_other_module 

titles, x_lists, y_lists = my_other_module.get_data() 

fig = plt.figure(figsize=(10,60)) 
for i, y_list in enumerate(y_lists): 
    plt.subplot(len(titles), 1, i) 
    plt.xlabel("Some X label") 
    plt.ylabel("Some Y label") 
    plt.title(titles[i]) 
    plt.plot(x_lists[i],y_list) 
fig.savefig('out.png', dpi=100) 

Respuesta

157

Puede utilizar plt.subplots_adjust para cambiar el espaciado entre las subtramas (source)

grito característico:

subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None) 

Los significados de los parámetros (y sugerido por defecto) son:

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 

Los valores predeterminados actuales son controlados por el archivo rc

+0

He intentado jugar con hspace, pero aumentarlo solo parece hacer todos los gráficos más pequeños sin resolver el problema de superposición. He intentado jugar con los otros parámetros también, pero no sé qué izquierda, derecha, abajo y arriba son realmente especificando allí. – mcstrother

+25

@mcstrother puede cambiar interactivamente los 6 de esos parámetros si hace clic en el botón 'ajustar' después de mostrar un gráfico, luego cópielos en el código una vez que encuentre lo que funciona. –

+0

No veo un botón de ajuste. Aunque estoy en un cuaderno de Jupyter. Intenté% matplotlib en línea y% matplotlib notebook. –

36

encontré que subplots_adjust (hspace = 0,001) es lo que terminó trabajando para mí. Cuando uso space = None, aún hay espacio en blanco entre cada gráfico. Sin embargo, establecerlo en algo muy cercano a cero parece forzarlos a alinearse. Lo que he subido aquí no es la pieza de código más elegante, pero se puede ver cómo funciona el hspace.

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.ticker as tic 

fig = plt.figure() 

x = np.arange(100) 
y = 3.*np.sin(x*2.*np.pi/100.) 

for i in range(5): 
    temp = 510 + i 
    ax = plt.subplot(temp) 
    plt.plot(x,y) 
    plt.subplots_adjust(hspace = .001) 
    temp = tic.MaxNLocator(3) 
    ax.yaxis.set_major_locator(temp) 
    ax.set_xticklabels(()) 
    ax.title.set_visible(False) 

plt.show() 

enter image description here

227

Trate de usar plt.tight_layout

Como un ejemplo rápido:

import matplotlib.pyplot as plt 

fig, axes = plt.subplots(nrows=4, ncols=4) 
fig.tight_layout() # Or equivalently, "plt.tight_layout()" 

plt.show() 

Sin Layout Tight

enter image description here


con diseño Tight enter image description here

+1

Esto es realmente genial. – Lokesh

+5

Sería un poco más claro si muestra que debe ejecutar esto después de su código de trazado, pero justo antes de mostrar() – MtRoad

+0

¡Esto funcionó para mí! ¡Gracias! –

25
import matplotlib.pyplot as plt 

fig = plt.figure(figsize=(10,60)) 
plt.subplots_adjust(...) 

El plt.subplots_adjust método:

def subplots_adjust(*args, **kwargs): 
    """ 
    call signature:: 

     subplots_adjust(left=None, bottom=None, right=None, top=None, 
         wspace=None, hspace=None) 

    Tune the subplot layout via the 
    :class:`matplotlib.figure.SubplotParams` mechanism. The parameter 
    meanings (and suggested defaults) are:: 

     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 

    The actual defaults are controlled by the rc file 
    """ 
    fig = gcf() 
    fig.subplots_adjust(*args, **kwargs) 
    draw_if_interactive() 

o

fig = plt.figure(figsize=(10,60)) 
fig.subplots_adjust(...) 

El tamaño de la imagen es importante.

"He intentado jugar con hspace, pero aumentarlo solo parece hacer todos los gráficos más pequeños sin resolver el problema de superposición."

así hacer más espacio en blanco y mantener el tamaño de las parcelas sub toda la imagen tiene que ser más grande.

+0

¡El tamaño de la imagen es importante, el tamaño de la imagen más grande puede resolver este problema! establecer 'plt.figure (figsize = (10, 7))', el tamaño de la imagen sería '2000 x 1400' pix – Belter

7

Usted podría intentar la subplot_tool()

plt.subplot_tool() 
+0

esto me salvó un montón de ajustes finos, nunca supe que sale gracias! –

+0

Ver https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplot_tool.html –

-1

no necesita más de ingeniero de aquí, simplemente use plt.tight_layout()

Cuestiones relacionadas