如何在matplotlib上绘制一个图例?

时间:2017-04-01 15:03:26

标签: python matplotlib plot legend

我在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_labels更改为headerheader = ["Label"],则会有效,但会打印出每个标签,如下图所示。

enter image description here

1 个答案:

答案 0 :(得分: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

您可以匹配您的颜色和标签,删除重复项,并为您的图例创建一些颜色补丁。

此外,您可以为传奇制作一些颜色点

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)

你会得到: enter image description here