How to add legend to scatter plot that has colour assignment

梦想与她 提交于 2019-12-11 06:39:07

问题


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


来源:https://stackoverflow.com/questions/42180475/how-to-add-legend-to-scatter-plot-that-has-colour-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!