ggplot2复制编辑离散Y轴并添加右侧第二标签的实现方法
你可以通过构建SampleID到sampleName的一一映射向量,再搭配scale_y_discrete()的sec.axis参数实现需求,完整修改后的代码如下:
library(tidyverse) # 构建SampleID到sampleName的匹配映射,两种写法二选一即可 # 写法1:tidyverse风格 name_map <- deframe(ddff[, c("SampleID", "sampleName")]) # 写法2:基础R兼容写法 # name_map <- setNames(as.character(ddff$sampleName), as.character(ddff$SampleID)) ddff %>% ggplot(aes(x = Counts, y = SampleID)) + geom_point(aes(col = compartment), size = 4, alpha = 0.75) + geom_text( aes(label = paste0(" ", Counts)), size = 3, hjust = 0, nudge_x = -0.1, check_overlap = TRUE, color = "blue" ) + xlim(NA, 33000) + # 新增次Y轴配置 scale_y_discrete( sec.axis = dup_axis( labels = name_map, name = "Sample Name" ) ) + theme_light() + theme(plot.title = element_text(hjust = 0.5), aspect.ratio = 1) + theme(# 移除垂直网格线 panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank()) + labs(title = "Library Size Overview", x = "Read Counts", y = "Sample ID", color = "Compartment") + theme( legend.position = c(.95, .95), legend.justification = c("right", "top"), legend.box.just = "right", legend.box.background = element_rect(color = "black", size = 1) )
补充说明
dup_axis()会完全复制主Y轴的刻度位置,仅替换标签和轴名,保证两侧标签一一对应,不需要额外调整刻度位置- 如果需要自定义右侧Y轴的文本样式,可以在
theme()中新增对应参数调整,例如:
theme( # 调整右侧Y轴标签颜色、大小 axis.text.y.right = element_text(color = "gray50", size = 9), # 调整右侧Y轴标题样式 axis.title.y.right = element_text(color = "gray30", size = 10) )
内容的提问来源于stack exchange,提问作者SteoG5972
相关产品推荐
相关产品推荐

