Una cosa che potresti cambiare nel tuo codice molto facilmente è quella fontsize
che stai usando per i titoli. Tuttavia, suppongo che tu non voglia semplicemente farlo!
Alcune alternative all'utilizzo fig.subplots_adjust(top=0.85)
:
Di solito tight_layout()
fa un ottimo lavoro nel posizionare tutto in buone posizioni in modo che non si sovrappongano. Il motivo tight_layout()
non aiuta in questo caso perché tight_layout()
non tiene conto di fig.suptitle (). C'è un problema aperto al riguardo su GitHub: https://github.com/matplotlib/matplotlib/issues/829 [chiuso nel 2014 a causa della necessità di un gestore della geometria completo - spostato su https://github.com/matplotlib/matplotlib/matplotlib/matplotlib / issues / 1109 ].
Se leggi la discussione, c'è una soluzione al tuo problema GridSpec
. La chiave è lasciare un po 'di spazio nella parte superiore della figura quando si chiama tight_layout
, usando il rect
kwarg. Per il tuo problema, il codice diventa:
Utilizzando GridSpec
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure(1)
gs1 = gridspec.GridSpec(1, 2)
ax_list = [fig.add_subplot(ss) for ss in gs1]
ax_list[0].plot(f)
ax_list[0].set_title('Very Long Title 1', fontsize=20)
ax_list[1].plot(g)
ax_list[1].set_title('Very Long Title 2', fontsize=20)
fig.suptitle('Long Suptitle', fontsize=24)
gs1.tight_layout(fig, rect=[0, 0.03, 1, 0.95])
plt.show()
Il risultato:
![usando gridspec](https://i.stack.imgur.com/u4Ecl.png)
Forse GridSpec
è un po 'eccessivo per te, o il tuo vero problema coinvolgerà molte più trame secondarie su una tela molto più grande, o altre complicazioni. Un semplice trucco è semplicemente usare annotate()
e bloccare le coordinate 'figure fraction'
per imitare un suptitle
. Tuttavia, potrebbe essere necessario apportare alcune modifiche più precise dopo aver dato un'occhiata all'output. Si noti che questa seconda soluzione non utilizza tight_layout()
.
Soluzione più semplice (anche se potrebbe essere necessario perfezionare)
fig = plt.figure(2)
ax1 = plt.subplot(121)
ax1.plot(f)
ax1.set_title('Very Long Title 1', fontsize=20)
ax2 = plt.subplot(122)
ax2.plot(g)
ax2.set_title('Very Long Title 2', fontsize=20)
# fig.suptitle('Long Suptitle', fontsize=24)
# Instead, do a hack by annotating the first axes with the desired
# string and set the positioning to 'figure fraction'.
fig.get_axes()[0].annotate('Long Suptitle', (0.5, 0.95),
xycoords='figure fraction', ha='center',
fontsize=24
)
plt.show()
Il risultato:
![semplice](https://i.stack.imgur.com/FvE2x.png)
[Utilizzo di Python
2.7.3 (64 bit) e matplotlib
1.2.0]