如何生成散点图并根据y值(取值1、2、3)为散点赋予不同颜色
实现方案
可以直接用matplotlib库的scatter方法完成需求,核心是将y轴的取值绑定到散点的颜色参数上,有两种常用实现方式:
基础自动配色方案
直接把y值传给c参数,matplotlib会自动为不同取值分配不同颜色,还可以通过cmap参数更换配色主题:
import matplotlib.pyplot as plt values = (1,1,2,2,3,2,1,3,3,2,1,3,2,1,1) x = range(len(values)) y = values plt.scatter(x, y, c=y, cmap='viridis', s=50) # s参数控制散点大小 # 添加颜色条说明取值和颜色的对应关系 plt.colorbar(ticks=[1,2,3], label='y取值') plt.xlabel('x') plt.ylabel('y') plt.show()
自定义固定配色方案
如果需要指定1、2、3分别对应具体颜色,可以先定义颜色映射规则,再生成每个点的颜色列表:
import matplotlib.pyplot as plt from matplotlib.lines import Line2D values = (1,1,2,2,3,2,1,3,3,2,1,3,2,1,1) x = range(len(values)) y = values # 自定义每个取值对应的颜色,可按需修改 color_map = {1: '#ff4444', 2: '#4488ff', 3: '#44dd44'} point_colors = [color_map[val] for val in y] plt.scatter(x, y, c=point_colors, s=50) # 添加自定义图例 legend_items = [ Line2D([], [], marker='o', color='w', markerfacecolor=color_map[1], markersize=10, label='1'), Line2D([], [], marker='o', color='w', markerfacecolor=color_map[2], markersize=10, label='2'), Line2D([], [], marker='o', color='w', markerfacecolor=color_map[3], markersize=10, label='3') ] plt.legend(handles=legend_items, title='y取值') plt.xlabel('x') plt.ylabel('y') plt.show()
内容的提问来源于stack exchange,提问作者miguel
相关产品推荐
相关产品推荐

