2012-10-06 48 views
37

我有一個繪圖,不同的顏色用於不同的參數,不同的線型用於不同的算法。目標是比較使用相似參數執行的不同算法的結果。這意味着我總共使用了4種不同的顏色和3種不同的線條樣式,在同一個圖表上共有12個圖。matplotlib:在同一個圖上的2個不同的圖例

我實際上建立了基於顏色的圖例,將每種顏色與相應的參數相關聯。現在我想在同一個圖上顯示第二個圖例,以及每種線條樣式的含義。有可能實現這一目標?怎麼樣?

這裏是我的代碼是什麼樣子實際上是:

colors = ['b', 'r', 'g', 'c'] 
cc = cycle(c) 
for p in parameters: 

    d1 = algo1(p) 
    d2 = algo2(p) 
    d3 = algo3(p) 

    pyplot.hold(True) 
    c = next(cc) 
    pyplot.plot(d1, '-', color=c, label="d1") 
    pyplot.plot(d1, '--', color=c) 
    pyplot.plot(d2, '.-', color=c) 

pyplot.legend() 

回答

53

有對確切主題的matplotlib文檔中的一個部分:http://matplotlib.org/users/legend_guide.html#multiple-legends-on-the-same-axes

這裏是爲您的具體示例代碼:

import itertools 
from matplotlib import pyplot 

colors = ['b', 'r', 'g', 'c'] 
cc = itertools.cycle(colors) 
plot_lines = [] 
for p in parameters: 

    d1 = algo1(p) 
    d2 = algo2(p) 
    d3 = algo3(p) 

    pyplot.hold(True) 
    c = next(cc) 
    l1, = pyplot.plot(d1, '-', color=c) 
    l2, = pyplot.plot(d2, '--', color=c) 
    l3, = pyplot.plot(d3, '.-', color=c) 

    plot_lines.append([l1, l2, l3]) 

legend1 = pyplot.legend(plot_lines[0], ["algo1", "algo2", "algo3"], loc=1) 
pyplot.legend([l[0] for l in plot_lines], parameters, loc=4) 
pyplot.gca().add_artist(legend1) 

下面是它的輸出示例: Plot with 2 legends, per-param and per-algo

+1

所以關鍵是在'add_artist'中...對於一些瘋狂的原因,matplotlib決定它知道更好並刪除原始圖例,然後你必須在稍後添加它。謝謝你的幫助,我會喝一杯啤酒。 –

5

這也是一個更「動手」的方式來做到這一點(即與任何數字軸)明確地互動:

import itertools 
from matplotlib import pyplot 

fig, axes = plt.subplot(1,1) 

colors = ['b', 'r', 'g', 'c'] 
cc = itertools.cycle(colors) 
plot_lines = [] 
for p in parameters: 

    d1 = algo1(p) 
    d2 = algo2(p) 
    d3 = algo3(p) 

    c = next(cc) 
    axes.plot(d1, '-', color=c) 
    axes.plot(d2, '--', color=c) 
    axes.plot(d3, '.-', color=c) 

# In total 3x3 lines have been plotted 
lines = axes.get_lines() 
legend1 = pyplot.legend([lines[i] for i in [0,1,2]], ["algo1", "algo2", "algo3"], loc=1) 
legend2 = pyplot.legend([lines[i] for i in [0,3,6]], parameters, loc=4) 
axes.add_artist(legend1) 
axes.add_artist(legend2) 

我喜歡寫它,因爲它允許潛在的較少模糊的方式與不同的軸玩這種方式。您可以先創建一組圖例,然後使用方法「add_artist」將它們添加到所需的座標軸。另外,我從matplotlib開始,對於我來說,至少在objets被解析時更容易理解腳本。

注意:請注意,您的傳說可能會在顯示/保存時被截斷。要解決這個問題,請使用方法axes.set_position([left,bottom,width,length])將子圖相對於圖的大小縮小並顯示圖例。

相關問題