2016-09-14 68 views
4

我正在使用matlibplot,我想手動添加項目到圖例是一種顏色和標籤。我將數據添加到圖中以指定會導致很多重複的情況。手動添加圖例項目Python matplotlib

我的想法是要做到:

ax2.legend(self.labels,colorList[:len(self.labels)]) 
    plt.legend() 

哪裏self.labels是我想要的那個傳說標貼的項目數發生大的顏色列表中的一個子集。但是,當我運行它時什麼也不會產生。

我錯過了什麼?

謝謝

+0

可能的重複[如何在matplotlib中自定義圖例](http://stackoverflow.com/questions/13303928/how-to-make-custom-legend-in-matplotlib) – gabra

回答

12

您是否已檢查Legend Guide

爲了實用性,我引用了guide的示例。

並非所有手柄都可以自動轉換爲圖例條目,因此它通常需要創建一個藝術家才能。圖形或軸上必須存在圖例句柄 才能使用。

假設我們要創造出有一些數據 這是由紅色表示的條目的傳說:

import matplotlib.patches as mpatches 
import matplotlib.pyplot as plt 

red_patch = mpatches.Patch(color='red', label='The red data') 
plt.legend(handles=[red_patch]) 

plt.show() 

enter image description here

編輯

要添加兩個補丁你可以這樣做:

import matplotlib.patches as mpatches 
import matplotlib.pyplot as plt 

red_patch = mpatches.Patch(color='red', label='The red data') 
blue_patch = mpatches.Patch(color='blue', label='The blue data') 

plt.legend(handles=[red_patch, blue_patch]) 

enter image description here

+1

這將如何工作,以添加多個?我可以製作一個補丁列表,然後只是做plt.legend(handles = patchList) –

+0

@Bradyforcier。 – gabra

+0

我試圖添加這樣的自定義補丁,並在圖例中看到兩個黑點和Patch'>。我嘗試添加上面的red_pa​​tch,並得到同樣的結果。補丁已添加爲plt.legend(mpatches.Patch(color ='red',label ='紅色數據'))。原來我卡住的版本是超級老0.99。不知道如何找出這個較老的API的工作原理 –

0

我最後寫了這一點:

def plot_bargraph_with_groupings(df, groupby, colourby, title, xlabel, ylabel): 
    """ 
    Plots a dataframe showing the frequency of datapoints grouped by one column and coloured by another. 
    df : dataframe 
    groupby: the column to groupby 
    colourby: the column to color by 
    title: the graph title 
    xlabel: the x label, 
    ylabel: the y label 
    """ 

    import matplotlib.patches as mpatches 

    # Makes a mapping from the unique colourby column items to a random color. 
    ind_col_map = {x:y for x, y in zip(df[colourby].unique(), 
           [plt.cm.Paired(np.arange(len(df[colourby].unique())))][0])} 


    # Find when the indicies of the soon to be bar graphs colors. 
    unique_comb = df[[groupby, colourby]].drop_duplicates() 
    name_ind_map = {x:y for x, y in zip(unique_comb[groupby], unique_comb[colourby])} 
    c = df[groupby].value_counts().index.map(lambda x: ind_col_map[name_ind_map[x]]) 

    # Makes the bargraph. 
    ax = df[groupby].value_counts().plot(kind='bar', 
             figsize=FIG_SIZE, 
             title=title, 
             color=[c.values]) 
    # Makes a legend using the ind_col_map 
    legend_list = [] 
    for key in ind_col_map.keys(): 
     legend_list.append(mpatches.Patch(color=ind_col_map[key], label=key)) 

    # display the graph. 
    plt.legend(handles=legend_list) 
    ax.set_xlabel(xlabel) 
    ax.set_ylabel(ylabel) 
1

我加入一些代碼的基礎上,從https://stackoverflow.com/users/2029132/gabra的答案,從https://stackoverflow.com/users/5946578/brady-forcier評論。在這裏,我通過 a'for'循環手動將元素添加到圖例

首先,我創建一個帶有我的圖例名稱和所需顏色的字典。通過字典

import matplotlib.patches as mpatches 
import matplotlib.pyplot as plt  

legend_dict = { 'data1' : 'green', 'data2' : 'red', 'data3' : 'blue' } 

然後我循環,併爲每個條目定義一個補丁並添加到列表,「PATCHLIST」:我真正做到這一點,因爲我在我的數據加載,但在這裏我只是明確定義。然後我使用這個列表來創建我的傳奇。

patchList = [] 
for key in legend_dict: 
     data_key = mpatches.Patch(color=legend_dict[key], label=key) 
     patchList.append(data_key) 

plt.legend(handles=patchList) 
plt.savefig('legend.png', bbox_inches='tight') 

這裏是我的輸出: legend example

我不打擾約圖例項以特定的順序是,但你很可能與

plt.legend(handles=sorted(patchList)) 

實現這一目標這是我第一次回答,所以提前道歉,任何錯誤/失禮。