[英]How to add legend to scatter plot that has colour assignment
I have an a list of x and y values and list of colour assignments for each point ('green', 'blue', 'red', etc). 我有一个x和y值列表以及每个点的颜色分配列表('green','blue','red'等)。 All of the examples I have found produce a legend based on separate plt.scatter() commands which later a simple plt.legend() suffices.
我发现的所有示例都基于单独的plt.scatter()命令生成一个图例,后来简单的plt.legend()就足够了。 making matplotlib scatter plots from dataframes in Python's pandas .
从Python的熊猫数据帧中制作matplotlib散点图 。 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')
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: 假设您有一个颜色列表
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.