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

基于X/Y轴阈值设置散点图点颜色及标签展示

解决方案

核心思路

先依据阈值给每个点分配分类与对应颜色,分批次绘制散点后,再给排名靠前的点添加标签。用Matplotlib即可实现需求,也可借助Seaborn简化代码。

Matplotlib实现代码

先导入依赖库:

import matplotlib.pyplot as plt
import pandas as pd

定义阈值(替换为你的实际阈值):

x_threshold = 0  # 自定义X轴阈值
y_threshold = 0.05  # 自定义Y轴阈值

生成每个点的分类与颜色映射:

def get_class(x_val, y_val):
    if y_val < y_threshold:
        return ("不显著", "#888888")
    elif x_val > x_threshold:
        return ("上升", "#ff0000")
    else:
        return ("下降", "#0000ff")

# 转换为DataFrame方便处理
df = pd.DataFrame({"x": x, "y": y, "label": z})
df[["category", "color"]] = df.apply(lambda row: get_class(row["x"], row["y"]), axis=1, result_type="expand")

绘制散点图并添加标签:

plt.figure(figsize=(10, 6))

# 按分类绘制散点
for cat in df["category"].unique():
    subset = df[df["category"] == cat]
    plt.scatter(subset["x"], subset["y"], color=subset["color"], label=cat, alpha=0.6)

# 给排名靠前的点加标签(示例按y值降序取前10,可自定义排序规则)
top_points = df.sort_values(by="y", ascending=False).head(10)
for _, row in top_points.iterrows():
    plt.text(row["x"], row["y"], row["label"], fontsize=8, ha="center", va="bottom")

# 完善图表元素
plt.legend()
plt.xlabel("X参数")
plt.ylabel("Y参数")
plt.title("分类散点图")
plt.grid(True, alpha=0.3)
plt.show()

Seaborn简化方案

如果想用更简洁的代码,可使用Seaborn:

import seaborn as sns

# 生成分类列
df["category"] = df.apply(lambda row: get_class(row["x"], row["y"])[0], axis=1)
color_map = {"不显著": "#888888", "上升": "#ff0000", "下降": "#0000ff"}

plt.figure(figsize=(10, 6))
sns.scatterplot(data=df, x="x", y="y", hue="category", palette=color_map, alpha=0.6)

# 添加top点标签
top_points = df.sort_values(by="y", ascending=False).head(10)
for _, row in top_points.iterrows():
    plt.text(row["x"], row["y"], row["label"], fontsize=8, ha="center", va="bottom")

plt.xlabel("X参数")
plt.ylabel("Y参数")
plt.title("分类散点图")
plt.grid(True, alpha=0.3)
plt.show()

关键调整说明

  • 颜色可替换为任意Matplotlib支持的颜色名称或十六进制码
  • 排名靠前的点筛选逻辑可自定义,比如按x绝对值、y绝对值排序
  • alpha参数控制点的透明度,避免点过多重叠导致视觉混乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:05:25