如何将图例添加到具有颜色分配的散点图 [英] How to add legend to scatter plot that has colour assignment
问题描述
我有一个x和y值的列表以及每个点(绿色",蓝色",红色"等)的颜色分配列表.我发现的所有示例都基于单独的plt.scatter()命令产生了一个图例,随后的一个简单plt.legend()就足够了. 从Python熊猫中的数据帧制作matplotlib散点图.我的散点图没有每个彩色组的单独散点图.那么,如何产生一个图例来显示每个组的颜色?
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')
推荐答案
假设您有颜色列表
colors = ["blue", "red", "green"]
和区域列表regions = ["Africa", "America", "Australia"]
您可以创建图例句柄列表并使用它来创建图例:
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')
这篇关于如何将图例添加到具有颜色分配的散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!