2012-04-27 19 views
11

Hay un similar question - pero no puedo hacer que la solución propuesta funcione.¿Cómo calzo el título largo?

He aquí un diagrama ejemplo con un título largo:

#!/usr/bin/env python 

import matplotlib 
import matplotlib.pyplot 
import textwrap 

x = [1,2,3] 
y = [4,5,6] 

# initialization: 
fig = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) 

# lines: 
fig.add_subplot(111).plot(x, y) 

# title: 
myTitle = "Some really really long long long title I really really need - and just can't - just can't - make it any - simply any - shorter - at all." 

fig.add_subplot(111).set_title("\n".join(textwrap.wrap(myTitle, 80))) 

# tight: 
(matplotlib.pyplot).tight_layout() 

# saving: 
fig.savefig("fig.png") 

da una

AttributeError: 'module' object has no attribute 'tight_layout' 

y si reemplazo (matplotlib.pyplot).tight_layout() con fig.tight_layout() da:

AttributeError: 'Figure' object has no attribute 'tight_layout' 

Así que mi pregunta es - ¿Cómo encajo el título de la trama?

+1

'tight_layout' es sólo en el último par de lanzamientos de matplotlib. Qué versión estás usando? Creo que 'tight_layout' se agregó en 1.1, aunque podría haber sido 1.0. –

+0

La mina es '1.0.1'. – Adobe

+0

@Joe Kington: Probablemente tengas razón: al reproducir Tu [respuesta] (http://stackoverflow.com/a/9604442/788700) aparece el mismo error. Estoy descargando la última fuente. – Adobe

Respuesta

35

Esto es lo que he usado por último:

#!/usr/bin/env python3 

import matplotlib 
from matplotlib import pyplot as plt 
from textwrap import wrap 

data = range(5) 

fig = plt.figure() 
ax = fig.add_subplot(111) 

ax.plot(data, data) 

title = ax.set_title("\n".join(wrap("Some really really long long long title I really really need - and just can't - just can't - make it any - simply any - shorter - at all.", 60))) 

fig.tight_layout() 
title.set_y(1.05) 
fig.subplots_adjust(top=0.8) 

fig.savefig("1.png") 

enter image description here

5

Una forma de hacerlo es simplemente cambiar el tamaño de fuente del título:

import pylab as plt 

plt.rcParams["axes.titlesize"] = 8 

myTitle = "Some really really long long long title I really really need - and just can't - just can't - make it any - simply any - shorter - at all." 
plt.title(myTitle) 
plt.show() 

enter image description here

En la respuesta que está vinculado varias otras soluciones que implican buenas nuevas líneas adición. ¡Incluso hay un automatic solution que cambia de tamaño según la figura!

+0

Eso es genial. +1 – Adobe

+1

@Adobe la página de inicio para personalizar matplotlib está aquí: http://matplotlib.sourceforge.net/users/customizing.html, ¡aunque ayuda si ya sabe lo que está buscando! – Hooked

+0

Esto funciona, pero es una mala solución. En su ejemplo, la fuente para el título es aún más pequeña que para las etiquetas de tic. Eso hará que el título sea muy difícil de leer en una publicación o presentación. – gerrit

Cuestiones relacionadas