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

如何为UMAP原型分析的xyplot点按时间着色并转为ggplot?

解决UMAP原型图的点上色与ggplot转换问题

一、给xyplot的点按时间上色

你可以通过archetypes包的xyplot函数的points.par参数实现按时间给点上色,步骤如下:

  1. 先把时间向量转成因子(让颜色按分组区分,而非连续值):
time_factor <- factor(my.time)
  1. 调用xyplot时,将颜色参数传入points.par:
xyplot(a, umapped$layout, 
       chull = chull(umapped$layout),
       points.par = list(col = time_factor))

如果需要自定义颜色(比如给时间"3"设蓝色、"7"设红色),可以先定义颜色向量再传入:

custom_cols <- c("3" = "blue", "7" = "red")
xyplot(a, umapped$layout, 
       chull = chull(umapped$layout),
       points.par = list(col = custom_cols[time_factor]))

二、转成ggplot绘制

用ggplot实现的话,需要手动整理数据、原型坐标和凸包信息,再分步绘制:

  1. 整理所有所需数据:
# 把UMAP坐标和时间合并为数据框
layout_df <- data.frame(
  UMAP1 = umapped$layout[,1],
  UMAP2 = umapped$layout[,2],
  time = factor(my.time)
)

# 提取原型的坐标
archetypes_df <- data.frame(
  UMAP1 = a$archetypes[,1],
  UMAP2 = a$archetypes[,2]
)

# 提取凸包坐标,重复第一个点让凸包闭合
chull_idx <- chull(umapped$layout)
chull_df <- layout_df[chull_idx, c("UMAP1", "UMAP2")]
chull_df <- rbind(chull_df, chull_df[1,])
  1. 使用ggplot绘制完整图形:
library(ggplot2)

ggplot() +
  # 绘制凸包(置于底层)
  geom_polygon(data = chull_df, aes(x=UMAP1, y=UMAP2), fill="gray80", alpha=0.3) +
  # 绘制原始数据点,按时间着色
  geom_point(data = layout_df, aes(x=UMAP1, y=UMAP2, color=time), size=2) +
  # 绘制原型点,用三角形状突出显示
  geom_point(data = archetypes_df, aes(x=UMAP1, y=UMAP2), shape=17, size=5, color="black") +
  # 使用简洁主题
  theme_bw() +
  # 设置坐标轴和图例标题
  labs(x="UMAP1", y="UMAP2", color="Time")

如果需要自定义时间分组的颜色,可添加scale_color_manual:

ggplot() +
  geom_polygon(data = chull_df, aes(x=UMAP1, y=UMAP2), fill="gray80", alpha=0.3) +
  geom_point(data = layout_df, aes(x=UMAP1, y=UMAP2, color=time), size=2) +
  geom_point(data = archetypes_df, aes(x=UMAP1, y=UMAP2), shape=17, size=5, color="black") +
  scale_color_manual(values = c("3" = "#1f77b4", "7" = "#ff7f0e")) +
  theme_bw() +
  labs(x="UMAP1", y="UMAP2", color="Time")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 00:35:19