How to add legend to scatter plot that has colour

2019-08-01 02:08发布

问题:

I have an a list of x and y values and list of colour assignments for each point ('green', 'blue', 'red', etc). All of the examples I have found produce a legend based on separate plt.scatter() commands which later a simple plt.legend() suffices. making matplotlib scatter plots from dataframes in Python's pandas. My scatter does not have separate scatters for each coloured group. So how do I produce a legend that shows the colours of each group?

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')

回答1:

Assuming you have a list of colors colors = ["blue", "red", "green"] and a list of regions regions = ["Africa", "America", "Australia"] you can create a list of legend handles and use it to create the legend:

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