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

如何在ggplot中将y轴数字替换为自定义加减符号

你只需要修改scale_y_continuous函数的labels参数,对原nloci的取值做符号映射即可,修改后的完整绘图代码如下:

library(tidyverse)

# 数据集构造
exampledf <- structure(list(male_diff = c(0.4668, -0.03299, 0.702, -0.11544, 
0.689, 0.511, -0.0725, -0.12844, -0.0827, 0.6515, -0.01077, 0.006, 
0.0041, -0.00856, 0.4181, -0.02765), female_diff = c(-0.459, 
0.022, -0.155, 0.00800000000000001, -0.156, -0.326, -0.0224, 
0.00700000000000001, 0.0399999999999999, 0.2182, -0.08458, 0.8844, 
-0.8459, 0.122, -0.506, 0.03), expt_in_ms = c(1, 1, 2, 2, 3, 
3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4), nloci = c(0, 20, 0, 20, 0, 
0, 0, 20, 20, 20, 0, 20, 0, 20, 0, 20), index = 1:16), row.names = c(NA, 
-16L), class = c("tbl_df", "tbl", "data.frame"))

ggplot(exampledf, aes(x = male_diff, y = index, color = as.factor(expt_in_ms))) + 
  geom_point(alpha = 0.5, size = 3) +
  geom_point(aes(x = female_diff), alpha = 0.8, shape = 24, size = 5) +
  # 核心修改:替换y轴标签,0对应加号,20对应减号
  scale_y_continuous(breaks = 1:nrow(exampledf), 
                     labels = ifelse(exampledf$nloci == 0, "+", "-")) +
  xlab("difference in proportion") +
  ylab("correlation") +
  geom_vline(
    xintercept = 0,
    color = 'black',
    linetype = 'dashed',
    alpha = .5
  ) +
  theme_minimal() + 
  theme(text = element_text(size = 12)) + 
  guides(alpha = FALSE, size = FALSE, shape = FALSE, color = FALSE)

额外优化说明:原代码中geom_point(aes(alpha = 0.5, size = 3))把固定参数写在aes()内是不必要的,会生成冗余的映射逻辑,上面的代码已经把这两个参数移到aes()外,不影响显示效果的同时代码更规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:24:04