如何调整Matplotlib中y轴分类数据顺序并绘制散点图及折线图
解决方案
核心思路
先完成数据的标签映射与过滤,再通过分类变量强制指定y轴的显示顺序,最后同时绘制散点图和折线图。
完整实现代码
import matplotlib.pyplot as plt import numpy as np import pandas as pd # 原始数据集 x = tuple(range(1, 41)) y_str = ('5', '2', '5', '2', '5', '2', '5', '2', '5', '2', '5', '2', '5', '2', '4', '2', '4', '2', '5', '1', '5', '2', '5', '2', '1', '3', '5', '0', '5', '3', '5', '3', '5', '3', '5', '3', '5', '3', '4', '0') # 定义标签映射规则 label_map = { '5': 'W', '4': 'R', '3': 'N1', '2': 'N2', '1': 'N1', '0': None # 0不显示,后续过滤 } # 转换标签并过滤无效数据 y_labels = [label_map[s] for s in y_str] filtered_x = [xi / 2 for xi, yl in zip(x, y_labels) if yl is not None] filtered_y = [yl for yl in y_labels if yl is not None] # 自定义y轴从上到下的显示顺序 custom_y_order = ['W', 'R', 'N1', 'N2', 'N3'] # 将y转换为分类变量,锁定顺序 filtered_y_cat = pd.Categorical(filtered_y, categories=custom_y_order, ordered=True) # 创建画布与轴对象 fig, ax = plt.subplots(figsize=(10, 6)) # 绘制折线图(用分类编码映射数值位置) ax.plot(filtered_x, filtered_y_cat.codes, color='#1f77b4', linestyle='-', label='折线图') # 绘制散点图 ax.scatter(filtered_x, filtered_y_cat.codes, color='#ff4b5c', s=60, label='散点图') # 设置y轴刻度与标签 ax.set_yticks(range(len(custom_y_order))) ax.set_yticklabels(custom_y_order) # 反转y轴,让自定义顺序从上到下展示 ax.invert_yaxis() # 设置图表基础信息 ax.set_xlabel('X (原始值 ÷ 2)') ax.set_ylabel('分类标签') ax.set_title('分类数据可视化') ax.legend() plt.tight_layout() plt.show()
关键细节说明
- 数据过滤:自动剔除y值为
0的条目,避免无效数据干扰图表 - 分类变量控制顺序:通过
pd.Categorical强制指定y轴标签的显示优先级,确保顺序符合需求 - y轴反转:Matplotlib默认y轴数值从下到上递增,反转后让自定义的第一个标签(W)显示在图表最上方
- 双图绘制:折线图用
plot函数,散点图用scatter函数,共享同一套轴刻度,保证数据对齐
内容的提问来源于stack exchange,提问作者AL B
相关产品推荐
相关产品推荐

