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

如何在ggplot2中绘制半长坐标轴(无需指定坐标)

在ggplot2中缩短坐标轴线条长度的通用方案

问题描述

需要在ggplot2中缩短X/Y轴的线条长度,使其呈现目标样式。现有方案需用geom_segment()指定线段起止坐标,希望获取仅关联格式、不依赖绘图内容的通用解决方案。

示例代码

library(Rtsne)
library(ggplot2)
data(iris)

tsne.res <- as.data.frame(Rtsne(as.matrix(iris[,1:4]), check_duplicates = FALSE)$Y)
colnames(tsne.res) <- c("x","y")

ggplot(tsne.res,
       mapping = aes(x = x, y = y)) +
  geom_point() +
  labs(x = "TSNE1", y = "TSNE2") +
  theme_bw() +
  theme(aspect.ratio = 1,
        panel.border = element_blank(),
        panel.grid = element_blank(),
        axis.line.x = element_line(arrow = arrow(type = "closed", length = unit(0.25, "cm"))),
        axis.line.y = element_line(arrow = arrow(type = "closed", length = unit(0.25, "cm"))),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.title.x = element_text(hjust = 0.05),
        axis.title.y = element_text(hjust = 0.05))

当前绘图

当前TSNE绘图

目标绘图

目标TSNE绘图

通用解决方案:利用guide_axis()实现轴截断

通过scale_x_continuous()和scale_y_continuous()中的guide = guide_axis(cap = 'upper')参数,结合分位数自动设置断点,可实现不依赖具体坐标的轴长度缩短。适配原始示例的代码如下:

ggplot(tsne.res,
       mapping = aes(x = x, y = y)) +
  geom_point() +
  labs(x = "TSNE1", y = "TSNE2") +
  theme_bw() +
  # 核心设置:用分位数定义断点,配合guide_axis截断轴
  scale_x_continuous(breaks = quantile(tsne.res$x, prob = 0.25), guide = guide_axis(cap = 'upper')) +
  scale_y_continuous(breaks = quantile(tsne.res$y, prob = 0.25), guide = guide_axis(cap = 'upper')) +
  theme(aspect.ratio = 1,
        panel.border = element_blank(),
        panel.grid = element_blank(),
        axis.line = element_line(arrow = arrow(type = "closed", length = unit(0.25, "cm"))),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.title.x = element_text(hjust = 0.05),
        axis.title.y = element_text(hjust = 0.05))

适配Seurat绘图的实现代码

dim1.gg <- DimPlot(sub.seurat, 
        reduction = "UMAP_PCA", 
        group.by = "dataset_fix", 
        label = FALSE, 
        raster = FALSE) + 
  scale_colour_manual(values = group2.cols) + 
  labs(title = "10x RNA", x = "UMAP1", y = "UMAP2")

dim1.gg + 
  scale_x_continuous(breaks = quantile(dim1.gg[[1]]$data$UMAPpca_1, prob = 0.25), guide = guide_axis(cap = 'upper')) +
  scale_y_continuous(breaks = quantile(dim1.gg[[1]]$data$UMAPpca_2, prob = 0.25), guide = guide_axis(cap = 'upper')) +
  
  theme(aspect.ratio = 1,
        panel.border = element_blank(),
        panel.grid = element_blank(),
        axis.line = element_line(arrow = arrow(type = "closed", length = unit(0.25, "cm"))),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.title = element_text(hjust = 0.15),
        legend.position = "none")

最终效果

最终UMAP绘图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:02:04