You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建Y轴刻度标签为自定义顺序的散点图

可以实现,用matplotlib即可快速完成该需求

核心思路是先将你指定的Y轴刻度顺序做值到坐标位置的映射,绘图时用映射后的坐标定位,最后替换Y轴刻度标签即可,完全满足你要求的自定义Y轴顺序、x-y值一一映射的需求。

完整实现代码

import matplotlib.pyplot as plt

# 你的自定义参数
y_order = [0, 7, 2, 9, 4, 11, 6, 1, 8, 3, 10, 5]
x_labels = ('a', 'b', 'c', 'd', 'e')
y_data = [[1,5,2], [10,5,11,7], [9], [], [7, 2, 9, 4, 11, 6, 1, 8, 3, 10, 5]]

# 建立y值到Y轴坐标位置的映射
y_val_to_pos = {val: idx for idx, val in enumerate(y_order)}

# 生成绘图用的坐标列表
x_plot = []
y_plot = []
for x_idx, y_vals in enumerate(y_data):
    for y_val in y_vals:
        x_plot.append(x_idx)
        y_plot.append(y_val_to_pos[y_val])

# 绘图
plt.figure(figsize=(6, 8))
plt.scatter(x_plot, y_plot, s=60, color='#1f77b4')

# 设置坐标轴
plt.xticks(range(len(x_labels)), x_labels)
plt.yticks(range(len(y_order)), y_order)
# 如果需要Y轴从上到下按你给出的顺序排列,和示例图效果一致,取消下一行注释即可
# plt.gca().invert_yaxis()

plt.grid(axis='y', linestyle='--', alpha=0.6)
plt.tight_layout()
plt.show()

实现说明

  • 没有直接用y的实际分数作为绘图坐标,而是先映射到你给定顺序的索引位置,保证Y轴的排列顺序完全符合你的要求
  • x值和y值按索引一一对应匹配,空的y列表(对应x值'd')不会生成散点,符合需求
  • 散点样式、大小、颜色都可以根据需要调整

内容的提问来源于stack exchange,提问作者David Lythgoe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 09:24:04