2010-12-01 16 views
23

¿es posible guardar (a un png) una subtrama individual en una figura matplotlib? Digamos que tengoGuardar una subtrama en matplotlib

import pylab as p 
ax1 = subplot(121) 
ax2 = subplot(122) 
ax.plot([1,2,3],[4,5,6]) 
ax.plot([3,4,5],[7,8,9]) 

¿Es posible salvar a cada una de las dos tramas secundarias a diferentes archivos o al menos una copia por separado a una nueva figura para salvarlos?

estoy usando la versión 1.0.0 de matplotlib en RHEL 5.

Gracias,

Robert

Respuesta

40

Mientras @Eli es del todo correcto que hay por lo general no es mucho de la necesidad de hacer es posible savefig toma un argumento bbox_inches que se puede usar para guardar selectivamente solo una parte de una figura en una imagen.

Aquí está un ejemplo rápido:

import matplotlib.pyplot as plt 
import matplotlib as mpl 
import numpy as np 

# Make an example plot with two subplots... 
fig = plt.figure() 
ax1 = fig.add_subplot(2,1,1) 
ax1.plot(range(10), 'b-') 

ax2 = fig.add_subplot(2,1,2) 
ax2.plot(range(20), 'r^') 

# Save the full figure... 
fig.savefig('full_figure.png') 

# Save just the portion _inside_ the second axis's boundaries 
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) 
fig.savefig('ax2_figure.png', bbox_inches=extent) 

# Pad the saved area by 10% in the x-direction and 20% in the y-direction 
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2)) 

La figura completa: Full Example Figure


Área dentro la segunda subtrama: Inside second subplot


la zona alrededor de la segunda subtrama acolchado en un 10% en la dirección x y el 20% en la dirección y: Full second subplot

+4

1: Wow! ¡Ojalá hubiera encontrado estos métodos mientras trato de aprender más sobre Matplotlib! Sería genial si la documentación oficial dirigiera lectores interesados ​​a estos rincones útiles de Matplotlib, y si la presentación de los conceptos relevantes fuera más estructurada. :) – EOL

+0

¡Muchas gracias, eso es lo que estaba buscando! –

+0

Un día en el que no aprende algo nuevo es un mal día ... Bien hecho ++ –

13

La aplicación de la función full_extent() en una respuesta por @ Joe 3 años después de here, se puede obtener exactamente lo que el OP estaba buscando. Como alternativa, puede utilizar Axes.get_tightbbox() lo que le da un poco más apretado cuadro delimitador

import matplotlib.pyplot as plt 
import matplotlib as mpl 
import numpy as np 
from matplotlib.transforms import Bbox 

def full_extent(ax, pad=0.0): 
    """Get the full extent of an axes, including axes labels, tick labels, and 
    titles.""" 
    # For text objects, we need to draw the figure first, otherwise the extents 
    # are undefined. 
    ax.figure.canvas.draw() 
    items = ax.get_xticklabels() + ax.get_yticklabels() 
# items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label] 
    items += [ax, ax.title] 
    bbox = Bbox.union([item.get_window_extent() for item in items]) 

    return bbox.expanded(1.0 + pad, 1.0 + pad) 

# Make an example plot with two subplots... 
fig = plt.figure() 
ax1 = fig.add_subplot(2,1,1) 
ax1.plot(range(10), 'b-') 

ax2 = fig.add_subplot(2,1,2) 
ax2.plot(range(20), 'r^') 

# Save the full figure... 
fig.savefig('full_figure.png') 

# Save just the portion _inside_ the second axis's boundaries 
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted()) 
# Alternatively, 
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted()) 
fig.savefig('ax2_figure.png', bbox_inches=extent) 

que había puesto una foto pero no tengo los puntos de reputación

+0

Esta respuesta se puede ampliar para incluir las etiquetas de texto añadiendo elementos + = [ax.get_xaxis(). Get_label(), ax.get_yaxis(). Get_label()]. Fueron cortados antes de agregar eso. – Erotemic

Cuestiones relacionadas