2017-04-01 172 views
0

我在matplotlib上繪製了一個圖表,並試圖創建一個圖例。我如何使用它用於區分我的數據類型的顏色標記來讓matplotlib創建自己的圖例?如何在matplotlib上繪製圖例?

我的數據是從csv文件中讀取的,該文件包含每種形狀的標籤。

My graph

我的代碼如下所示:

data_df = pd.DataFrame.from_csv("AllMixedShapes2.csv") 
    X1 = np.array(data_df[features2].values) 
    y1 = np.array(data_df[features3].values) 

    plt.scatter(X1[:, 0],y1, c=y, cmap=plt.cm.Paired) 
    plt.axis([0, 17, 0, 200]) 
    plt.ylabel("Maximum Angle (Degrees)") 
    plt.xlabel("Number Of Sides") 
    plt.title('Original 450 Test Shapes') 

    plt.legend() 
    plt.show() 

我已經試過這樣:

handles, labels = ax.get_legend_handles_labels() 
ax.legend(handles, labels) 

但我不斷收到此錯誤:

handles, labels = ax.get_legend_handles_labels() 
UnboundLocalError: local variable 'ax' referenced before assignment 

編輯:

我嘗試這樣做:

features_of_labels = ["Circle", "Equilateral Triangle", "Right Angle Triangle", 
        "Obtuse Triangle", "Acute Triangle", "Square", "Rectangle", 
        "Parallelogram", "Seal"] 

data_df = pd.DataFrame.from_csv("AllMixedShapes2.csv") 
X1 = np.array(data_df[features2].values) 
y1 = np.array(data_df[features3].values) 
l = np.array(data_df[features_of_labels].values) 

,但我得到以下錯誤: KeyError異常:「['圈'正三角形'直角三角 '鈍角三角形' \ n'急性三角」廣場''長方形‘平行四邊形’‘印章’]不是指數」

但是如果我改變features_of_labelsheaderheader = ["Label"]它的工作原理,但打印出的標籤上所示一樣,在未來的畫面。

enter image description here

+0

嘗試'AX = plt.gca:

更進一步,可以使顏色一些點爲你的傳奇

lables_patchs = [] for item in c_l: # here, use scatter() add_patch = plt.scatter([],[],color=item[0], label=item[1]) lables_patchs.append(add_patch) 

,你會得到。 – bernie

+0

@bernie我得到這個錯誤:'UserWarning:找不到標記的對象。在個人情節上使用標籤='...'kwarg。' –

+1

你是否做了警告告訴你的事情?你還應該看看[問題1](問題2)(http://stackoverflow.com/questions/37812325/pandas-scatter-plot-with-different-color-legend-for-each-point), http://stackoverflow.com/questions/30505407/create-legend-for-scatter-plot-using-the-label-of-the-samples-in-matplotlib)和[問題3](http:// stackoverflow .com/questions/8017654/how-to-add-legend-for-scatter)並使用獲得的知識改善您的問題。你想達到什麼目的,以及這些技術對你有多大幫助? – ImportanceOfBeingErnest

回答

0

下面是一個例子:

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


# data for example 
y1 = [i for i in range(10)] 
y2 = [i for i in range(10)] 
colors = ['m','b','g','m','b','g','m','b','g','g'] 
lables = ['m','b','g','m','b','g','m','b','g','g'] 

plt.scatter(y1, y2,c=colors, cmap=plt.cm.Paired) 

# Match colors and labels,remove duplicates 
colors_lables = zip(colors, lables) 
colors_lables = list(set(colors_lables)) 
lables = [lable for color,lable in colors_lables] 

# create some patchs of colors 
lables_patchs = [] 
for item in c_l: 
    add_patch = mpatches.Patch(color=item[0], label=item[1]) 
    lables_patchs.append(add_patch) 

plt.legend(lables_patchs, lables) 

plt.show() 

而且圖片中我們得到: enter image description here

你可以匹配你的顏色和標貼,刪除重複項,創造的顏色卻有些斑塊爲你的傳奇。 ()`在該行之前 enter image description here

+0

我顯示了我的嘗試編輯的問題。你知道我做錯了什麼嗎? –

+0

我修復了答案,並且有一個例子,希望能夠幫到你。 – xiaoyi