2013-01-15 8 views
20

Ich habe den folgenden Beispielcode:Einzel Legende für mehrere Achsen

fig1.suptitle('Test') 
ax1 = fig1.add_subplot(221) 
ax1.plot(x,y1,color='b',label='aVal') 
ax2 = ax1.twinx() 
ax2.plot(x,y2,color='g',label='bVal') 
ax2.grid(ls='--', color='black') 
legend([ax1,ax2], loc=2) 

Die subplot hat zwei Achsen mit unterschiedlichen Skalen auf der gleichen subplot und ich möchte nur eine Legende für beide Achsen. Ich habe den obigen Code ausprobiert und es funktioniert nicht und erzeugt nur Details von ax2. Irgendwelche Ideen?

+0

Siehe http://stackoverflow.com/questions/5484922/secondary- axis-with-twinx-how-to-legende für dieselbe Frage hinzufügen. Und gibt auch die selbe Lösung. – joris

+1

Ja, tut es. Meine Suche nach SO brachte es nicht zur Sprache. Die Frage besagt auch nicht, dass eine einzelne Legende über den Titel benötigt wird. Aber danke, dass du mich informiert hast. Ich fragte mich, ob es etwas Eleganteres gab, als das, was mir einfiel. Vielleicht sollten wir eine ax1.combine_legends (ax2) -Methode hinzufügen, die das tut? – arun

Antwort

43

Ich dachte, es ist eine Lösung, die funktioniert! Gibt es einen besseren Weg als das?

fig1.suptitle('Test') 
ax1 = fig1.add_subplot(221) 
ax1.plot(x,y1,color='b',label='aVal') 
ax2 = ax1.twinx() 
ax2.plot(x,y2,color='g',label='bVal') 
ax2.grid(ls='--', color='black') 
h1, l1 = ax1.get_legend_handles_labels() 
h2, l2 = ax2.get_legend_handles_labels() 
ax1.legend(h1+h2, l1+l2, loc=2) 
+0

das funktioniert für mich! – gnr

1

Dies ist in der Tat eine alte Post, aber ich denke, ich fand einen einfacheren Weg, der mehr Kontrolle erlaubt.

Hier ist (matplotlib Version '1.5.3'.) Auf python3.5:

import matplotlib.pyplot as plt 
fig, ax1 = plt.subplots() 
plt.suptitle('Test') 
ax2 = ax1.twinx() 
a, = ax1.plot([1, 2, 3], [4, 5, 6], color= 'blue', label= 'plt1') 
b, = ax2.plot([7, 8, 9],[10, 11, 12], color= 'green', label= 'plt2') 
p = [a, b] 
ax1.legend(p, [p_.get_label() for p_ in p], 
      loc= 'upper center', fontsize= 'small') 

show()

Verwandte Themen