如何用matplotlib按另一列表标签为点列表设置不同颜色绘图?
使用Matplotlib按标签为点设置不同颜色绘图
基础实现(自动分配颜色)
如果你的标签是整数或可哈希的分类值(比如字符串),可以直接用plt.scatter()的c参数传入标签列表,Matplotlib会自动为不同标签分配不同颜色:
import matplotlib.pyplot as plt # 示例数据 points = [(1, 2), (3, 4), (5, 1), (2, 5), (4, 3)] labels = [0, 1, 0, 2, 1] # 标签也可以是字符串,比如['A','B','A','C','B'] # 拆分x和y坐标 x = [p[0] for p in points] y = [p[1] for p in points] # 按标签绘图 plt.scatter(x, y, c=labels, cmap='viridis') # cmap指定颜色映射,可选 # 添加基础元素 plt.xlabel('X 坐标') plt.ylabel('Y 坐标') plt.title('按标签着色的散点图') plt.colorbar(label='标签') # 数值标签适合显示颜色条,分类标签可省略 plt.show()
自定义颜色与图例(分类标签友好)
如果需要自定义颜色或为每个标签添加清晰的图例,建议按标签分组后分别绘图:
import matplotlib.pyplot as plt from collections import defaultdict # 示例数据 points = [(1, 2), (3, 4), (5, 1), (2, 5), (4, 3)] labels = ['猫', '狗', '猫', '鸟', '狗'] # 自定义颜色映射 color_map = {'猫': '#FF6B6B', '狗': '#4ECDC4', '鸟': '#45B7D1'} # 按标签分组点 grouped_points = defaultdict(list) for point, label in zip(points, labels): grouped_points[label].append(point) # 逐组绘图 for label, pts in grouped_points.items(): x = [p[0] for p in pts] y = [p[1] for p in pts] plt.scatter(x, y, color=color_map[label], label=label) # 添加图例和基础元素 plt.xlabel('X 坐标') plt.ylabel('Y 坐标') plt.title('自定义颜色的分类散点图') plt.legend(title='类别') plt.show()
关键说明
c参数:接受数值列表或分类列表,数值会映射到指定的颜色映射表,分类值会被自动编码为整数后着色。cmap:指定预定义的颜色映射(如viridis、tab10),适用于数值标签或需要高区分度的场景。- 分组绘图:更适合分类标签场景,能精准控制每个类别的颜色,且方便添加直观的图例。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

