簡體   English   中英

如何在matplotlib上繪制圖例?

[英]How to plot a legend on matplotlib?

我已經在matplotlib上繪制了一個圖形,並試圖創建一個圖例。 我如何使用matplotlib用來區分數據類型的顏色標記來創建自己的圖例?

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

我的圖

我的代碼如下所示:

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:“ ['圓''等邊三角形''直角三角形''Obtuse三角形'\\ n'急性三角形''平方''矩形''平行四邊形''密封']不在索引中”

但是,如果我將features_of_labels更改為headerheader = ["Label"]它可以工作,但會打印出每個標簽,如下圖所示。

在此處輸入圖片說明

這是一個例子:

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()

我們得到的圖片是: 在此處輸入圖片說明

您可以匹配顏色和標簽,刪除重復項,並為圖例創建一些色塊。

此外,您可以為圖例添加一些顏色

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)

你會得到: 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM