如何在matplotlib中使用分类boardid列为散点图设置不同颜色
matplotlib按分类变量
boardid为散点着色的实现方法 核心逻辑是对不同boardid的分组数据分别指定颜色绘制,有两种常用实现方案:
方案1:遍历分组分别绘图(逻辑最直观)
直接提取所有唯一的boardid值,为每个值分配对应颜色后逐组绘制散点,修改后的完整代码如下:
# 原有数据过滤逻辑保持不变 t_min = data.index.min() t_max = pd.Timestamp('2015-01-01') plt.figure(figsize=(18,5)) plt.xlim(t_min, t_max) location_filter = data.location == 'Fitzroy Gardens' time_filter = data.index < t_max data_filtered = data[location_filter & time_filter] # 新增着色逻辑 # 提取所有唯一的boardid unique_boards = data_filtered['boardid'].unique() # 自定义5种颜色,可根据需求调整,也可直接使用matplotlib默认颜色循环 custom_colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd'] for board_id, color in zip(unique_boards, custom_colors): # 筛选当前boardid对应的数据子集 current_subset = data_filtered[data_filtered['boardid'] == board_id] # 绘制散点,添加label用于生成图例 plt.plot(current_subset.index, current_subset.temp_avg, ',', c=color, alpha=.9, label=f'Board {board_id}') # 添加图例区分不同boardid的颜色 plt.legend() plt.show()
方案2:使用scatter方法映射分类编码(代码更简洁)
将分类变量boardid转为数值编码后直接传入scatter的c参数,配合颜色映射表实现着色:
# 数据过滤逻辑同方案1 t_min = data.index.min() t_max = pd.Timestamp('2015-01-01') plt.figure(figsize=(18,5)) plt.xlim(t_min, t_max) location_filter = data.location == 'Fitzroy Gardens' time_filter = data.index < t_max data_filtered = data[location_filter & time_filter] unique_boards = data_filtered['boardid'].unique() # 将boardid转为数值编码 data_filtered['board_code'] = pd.factorize(data_filtered['boardid'])[0] # 绘制散点,使用tab10色系匹配5个分类值 plt.scatter( x=data_filtered.index, y=data_filtered.temp_avg, c=data_filtered['board_code'], cmap='tab10', alpha=0.9, marker=',' ) # 生成自定义图例 legend_handles = [ plt.Line2D([], [], marker=',', color='w', markerfacecolor=plt.cm.tab10(idx), markersize=10, label=f'Board {bid}') for idx, bid in enumerate(unique_boards) ] plt.legend(handles=legend_handles) plt.show()
两种方案都可以实现5个boardid对应5种不同颜色的效果,方案1适合需要精细调整每个分类样式的场景,方案2适合分类数量较多的场景。
内容的提问来源于stack exchange,提问作者latarara
相关产品推荐
相关产品推荐

