如何将图例添加到具有颜色分配的散点图

How to add legend to scatter plot that has colour assignment

我有一个 x 和 y 值列表以及每个点的颜色分配列表('green'、'blue'、'red' 等)。我发现的所有示例都会根据单独的 plt.scatter() 命令生成一个图例,稍后一个简单的 plt.legend() 就足够了。 making matplotlib scatter plots from dataframes in Python's pandas。我的散点图没有针对每个彩色组的单独散点图。那么我如何制作一个显示每组颜色的图例呢?

import matplotlib.pyplot as plt

colors = ["red", "orange", "green", "blue", "purple", "gray"]
regions = ["Hanoi", "Nha Trang", "Vung Tau", "Phu Quoc", "Quang Ngai", "Saigon"]
region_colors=dict(zip(regions,colors))

grp_color=[]
for i in data['Region']:
    grp_color.append(region_colors[i]) 

x_long=data[' Longitude']
y_lat=data[" Latitude"]
plt.scatter(x_long,y_lat,c=grp_color)
plt.legend(grp_color,regions,loc='right')

假设你有一个颜色列表 colors = ["blue", "red", "green"] 和区域列表 regions = ["Africa", "America", "Australia"] 您可以创建图例句柄列表并使用它来创建图例:

handlelist = [plt.plot([], marker="o", ls="", color=color)[0] for color in colors]
plt.legend(handlelist,regions,loc='right')