2016-03-16 22 views
5

Supponiamo di avere un'istanza gridspec di matplotlib in uno script python. Quello che voglio fare è creare due assi e avere la trama in un asse e la legenda nell'altro. Qualcosa comeLegenda matplotlib di Python su asse separato con gridspec

import numpy as np 
from matplotlib import gridspec, pyplot as plt 

x = np.linspace(0,100) 
y = np.sin(x) 

gs = gridspec.GridSpec(100, 100) 
ax1 = fig.add_subplot(gs[ :50, : ]) 
ax2 = fig.add_subplot(gs[ 55:, : ]) 
ax1.plot(s, y, label=r'sine') 
ax2.legend() # ?? Here I want legend of ax1 
plt.show() 

C'è qualche modo per farlo?

risposta

4

È possibile prendere le maniglie delle leggende e le etichette dalla prima sottotrama utilizzando ax1.get_legend_handles_labels() e quindi utilizzarle quando si crea la legenda sulla seconda sottotrama.

Dal docs:

get_legend_handles_labels(legend_handler_map=None)

maniglie di ritorno ed etichette per leggenda

ax.legend() è equivalente a:

h, l = ax.get_legend_handles_labels() 
ax.legend(h, l) 
import numpy as np 
from matplotlib import gridspec, pyplot as plt 

x = np.linspace(0,100) 
y = np.sin(x) 

fig = plt.figure() 

gs = gridspec.GridSpec(100,100) 
ax1 = fig.add_subplot(gs[ :50, : ]) 
ax2 = fig.add_subplot(gs[ 55:, : ]) 

ax1.plot(x, y, label=r'sine') 

h,l=ax1.get_legend_handles_labels() # get labels and handles from ax1 

ax2.legend(h,l)      # use them to make legend on ax2 

plt.show() 

enter image description here

Problemi correlati