我在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异常:“['圈'正三角形'直角三角 '钝角三角形' \ n'急性三角”广场''长方形‘平行四边形’‘印章’]不是指数”
但是如果我改变features_of_labels
到header
和header = ["Label"]
它的工作原理,但打印出的标签上所示一样,在未来的画面。
尝试'AX = plt.gca:
更进一步,可以使颜色一些点为你的传奇
,你会得到。 – bernie
@bernie我得到这个错误:'UserWarning:找不到标记的对象。在个人情节上使用标签='...'kwarg。' –
你是否做了警告告诉你的事情?你还应该看看[问题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