2017-04-01 166 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