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

如何在R的ggplot2中用小箭头替代UMAP图的坐标轴?

用ggplot2复现单细胞测序图的左下角小箭头坐标轴样式

要实现单细胞RNA测序文献中常见的「左下角小箭头替代坐标轴+箭头旁侧标题」的专业样式,核心思路是隐藏ggplot2默认的坐标轴元素,再手动添加自定义箭头和轴标题。以下是具体实现步骤:

1. 准备示例数据

以PCA分析结果为例(UMAP/t-SNE的实现逻辑完全一致):

library(ggplot2)
library(stats)

# 对iris数据集做PCA降维
iris_pca <- prcomp(iris[,1:4], scale. = TRUE)
pca_df <- data.frame(
  PC1 = iris_pca$x[,1],
  PC2 = iris_pca$x[,2],
  Species = iris$Species
)

2. 绘制基础散点图并隐藏默认坐标轴

先画出核心散点图,移除默认的坐标轴相关元素:

base_plot <- ggplot(pca_df, aes(x = PC1, y = PC2, color = Species)) +
  geom_point(size = 2) +
  theme_minimal() +
  theme(
    # 隐藏默认轴标题、刻度文本、刻度线和轴线
    axis.title = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    axis.line = element_blank(),
    # 可选:调整图例位置
    legend.position = "right"
  )

3. 添加左下角自定义小箭头

用geom_segment()绘制箭头,通过arrow参数控制箭头样式:

arrow_plot <- base_plot +
  # X轴箭头(向右)
  geom_segment(
    x = min(pca_df$PC1) * 0.95, xend = min(pca_df$PC1) * 0.8,
    y = min(pca_df$PC2) * 0.95, yend = min(pca_df$PC2) * 0.95,
    arrow = arrow(length = unit(0.15, "cm"), type = "closed"), # 箭头长度和实心样式
    color = "black", linewidth = 0.8
  ) +
  # Y轴箭头(向上)
  geom_segment(
    x = min(pca_df$PC1) * 0.95, xend = min(pca_df$PC1) * 0.95,
    y = min(pca_df$PC2) * 0.95, yend = min(pca_df$PC2) * 0.8,
    arrow = arrow(length = unit(0.15, "cm"), type = "closed"),
    color = "black", linewidth = 0.8
  )
  • 乘数(如0.95、0.8)用于微调箭头的起始和结束位置,可根据实际数据调整
  • 若需要空心箭头,将type="closed"改为type="open"即可

4. 添加轴标题

用annotate()在箭头旁添加轴标题,调整位置使其对齐:

final_plot <- arrow_plot +
  # PC1标题(箭头下方)
  annotate(
    "text",
    x = min(pca_df$PC1) * 0.85, y = min(pca_df$PC2) * 1.05,
    label = "PC1", hjust = 0.5, vjust = 1, size = 4
  ) +
  # PC2标题(箭头右侧,垂直排列)
  annotate(
    "text",
    x = min(pca_df$PC1) * 1.05, y = min(pca_df$PC2) * 0.85,
    label = "PC2", hjust = 1, vjust = 0.5, size = 4, angle = 90
  )

print(final_plot)

关键调整技巧

  • 若使用UMAP/t-SNE数据,只需替换pca_df为对应的降维结果数据框即可
  • 可通过修改color、linewidth、size等参数,匹配目标文献的样式风格
  • 箭头和标题的位置可通过调整乘数或直接设置固定数值来优化

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:21:29