如何在python的散点图中添加具有不同标记的多个图例?

时间:2020-03-17 08:58:06

标签: python matplotlib legend scatter-plot

link 可接受的答案说明了如何绘制散点图以进行二进制分类。但没有说明如何更改标记的默认颜色。所以我写下面的代码来改变标记的颜色

import matplotlib.colors as mcolors
plt.figure(num=0, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')

x=df.iloc[:,0:1].values
y=df.iloc[:,1:2].values
z=df.iloc[:,2:3].values

l=plt.scatter(x,y, c=z,cmap = mcolors.ListedColormap(["blue", "red"]),marker='+')
plt.xlabel('Exam 1 score',fontsize=14)
plt.ylabel('Exam 2 score',fontsize=14)
# Turn on the minor TICKS, which are required for the minor GRID
plt.minorticks_on()

# Customize the major grid
plt.grid(which='major', linestyle='-', linewidth='0.5', color='black')
# Customize the minor grid

plt.grid(which='minor', linestyle=':', linewidth='0.5', color='blue')
plt.legend((l,l),("Admitted", "Not Admitted"), loc="upper right")
plt.show()  

但是现在我尝试将图例添加为plt.legend((l,l),("Admitted", "Not Admitted"), loc="upper right"),结果如图所示。为此,我在here的帮助下,他们绘制了多个散点图,但就我而言,我只有一个散点图。

enter image description here

但是,如上图所示,图例中两个标记的标记颜色相同。因此,我的问题是如何通过在散点图中使用 plt.legend()来添加具有不同标记颜色或不同标记的多个图例?

1 个答案:

答案 0 :(得分:2)

从matplotlib 3.1开始,您可以使用散点图的legend_elements()来简化图例的创建。

import matplotlib.colors as mcolors
plt.figure(num=0, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')

x=np.random.random(size=(10,))
y=np.random.random(size=(10,))
z=np.random.choice([0,1], size=(10,))

s = plt.scatter(x,y, c=z,cmap = mcolors.ListedColormap(["blue", "red"]),marker='+')
plt.xlabel('Exam 1 score',fontsize=14)
plt.ylabel('Exam 2 score',fontsize=14)
# Turn on the minor TICKS, which are required for the minor GRID
plt.minorticks_on()

# Customize the major grid
plt.grid(which='major', linestyle='-', linewidth='0.5', color='black')
# Customize the minor grid

plt.grid(which='minor', linestyle=':', linewidth='0.5', color='blue')
h,l = s.legend_elements()
plt.legend(h,("Admitted", "Not Admitted"))

enter image description here

更多examples here