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

ggparcoord绘制平行坐标图:指定首列时文本标签转数字问题求助

问题描述

在使用ggparcoord绘制平行坐标图时,尝试在第一列(time1)左侧添加对应SeqName标签,采用@Allan Cameron的方案时出现异常:指定第一列作为标签位置时,文本标签被转换为数字;但指定第二列时显示正常。

原因分析

ggparcoord会将输入数据转换为长格式进行绘图,其中variable列是因子类型。当你在geom_text_repel的美学映射(aes)中使用ifelse(variable == "time1", as.character(SeqName), "")时:

  • ggplot会自动将混合了非空字符串与空字符串的向量转换为因子
  • 原本的SeqName字符标签会被转换为因子的整数编码(也就是你看到的数字)
  • 当指定第二列(time2)时,空字符串对应的行不在该x轴位置的可视区域,因此不会显示错误的数字标签
解决方案

不要在aes中使用ifelse进行条件判断,直接过滤出variable为time1的行作为geom_text_repel的数据源,避免类型转换问题:

# 创建测试数据
data3 <- tibble(
  SeqName = paste(rep(c("Gene1", "Gene2", "Gene3"), 3)),
  type = c(rep("nonresponder", 3), rep("norm responder", 3), rep("high responder", 3)),
  time1 = rnorm(9, 2, 0.5),
  time2 = rnorm(9, 4, 1),
  time3 = rnorm(9, 6, 1)
)

# 绘制平行坐标图
ggparcoord(
  data = data3,
  columns = 3:5,
  groupColumn = 2,
  showPoints = FALSE,
  splineFactor = FALSE,
  alphaLines = 1,
  boxplot = TRUE
) +
  # 过滤出time1对应的行来绘制标签
  geom_text_repel(
    data = . %>% filter(variable == "time1"),
    aes(label = SeqName),
    hjust = 1.2,
    size = 5,
    direction = "y"
  ) +
  theme(text = element_text(size = 15))

也可以提前提取长格式数据并过滤,再传入绘图函数:

# 先转换为长格式并过滤目标行
plot_data <- ggparcoord(
  data = data3,
  columns = 3:5,
  groupColumn = 2,
  showPoints = FALSE,
  splineFactor = FALSE,
  alphaLines = 1,
  boxplot = TRUE
)$data %>% filter(variable == "time1")

# 绘制平行坐标图并添加标签
ggparcoord(
  data = data3,
  columns = 3:5,
  groupColumn = 2,
  showPoints = FALSE,
  splineFactor = FALSE,
  alphaLines = 1,
  boxplot = TRUE
) +
  geom_text_repel(
    data = plot_data,
    aes(label = SeqName),
    hjust = 1.2,
    size = 5,
    direction = "y"
  ) +
  theme(text = element_text(size = 15))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:14:54