简体   繁体   English

如何在 plot 中制作图例?

[英]How to make a legend in a plot?

I am unable to figure out a way to get a legend of my plot. My data is a data frame consisting of 3 columns x, y and z.我无法找到一种方法来获取我的 plot 的图例。我的数据是一个由 3 列 x、y 和 z 组成的数据框。 x and y represent the co-ordinates of a point and z is the label(0,1,2,3) that the point belongs to. x 和 y 表示点的坐标,z 是该点所属的标签(0,1,2,3)。 Sample data:样本数据:

在此处输入图像描述

I need to plot a scatterplot with a legend containing a colour representing a respective label. I have plotted the scatterplot but am unable to understand how to put the legend in it.我需要 plot 散点图,其中包含代表相应 label 的颜色的图例。我已经绘制了散点图,但无法理解如何将图例放入其中。 The code I used till now is(dft is the dataframe):到目前为止我使用的代码是(dft 是数据框):

import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot()
ax.scatter(dft['x'] , dft['y'], c=dft['z'], cmap = 'hsv')
plt.show()

The figure I obtained is:我得到的图是:

在此处输入图像描述

I need a legend for each color.我需要每种颜色的图例。

You can try this code instead:您可以尝试使用此代码:

import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize=(8,8))
plt.scatter(dft['x'] , dft['y'], c=dft['z'], cmap = 'hsv')
plt.colorbar()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM