如何在ggplot2中为X轴两端添加双标签?
实现ggplot X轴两端显示Low/High标签
问题背景
现有数据框scenario_data结构如下:
name x y Scenario 1 0.5 0.5 Scenario 2 0.2 0.2 Scenario 3 0.8 0.2 Scenario 4 0.2 0.8
当前绘图代码生成的图表中,X轴只有中间的"Middle"标签,需要替换为左侧显示"Low"、右侧显示"High"的两端标签。
原绘图代码
library(tidyverse) library(ggrepel) scenario_data <- read.csv("scatter_plot.csv", header = T) tiff("scenario_plot.tiff", units="in", width=5, height=5, res=300) scenarios_plot <- ggplot(scenario_data, aes(x = x, y = y)) + geom_point(colour = "#93358D", size = 3) + labs(title = "Figure 1: Four \n Scenarios", x = "Middle", y = "Scale of \n Intervention") scenarios_plot + geom_label_repel(aes(label = name), box.padding = 0.35, point.padding = 0.5, segment.color = "grey50") + theme_classic() + theme(axis.text.x=element_blank(), axis.title.y=element_text(angle = 0), axis.ticks.x=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(), plot.title = element_text(hjust=0.5), axis.line = element_line(arrow = arrow(angle = 15, length = unit(0.15, "inches"), type = "closed"))) dev.off()
(注:原代码存在labs()未闭合的语法错误,已补充修正)
解决方案
通过annotate()直接在X轴两端添加文本标签,同时移除原X轴标题,具体步骤如下:
- 移除原X轴标题,将
labs()中的x = "Middle"改为x = NULL - 使用
annotate()分别在X轴左端(x=0位置)和右端(x=1位置)添加"Low"和"High"标签,调整y值让标签对齐到轴下方 - 增加底部绘图边距,避免标签被截断
修正后的完整代码
library(tidyverse) library(ggrepel) scenario_data <- read.csv("scatter_plot.csv", header = T) tiff("scenario_plot.tiff", units="in", width=5, height=5, res=300) scenarios_plot <- ggplot(scenario_data, aes(x = x, y = y)) + geom_point(colour = "#93358D", size = 3) + labs(title = "Figure 1: Four \n Scenarios", x = NULL, # 移除原X轴标题 y = "Scale of \n Intervention") + geom_label_repel(aes(label = name), box.padding = 0.35, point.padding = 0.5, segment.color = "grey50") + # 添加两端标签 annotate("text", x = 0, y = -0.05, label = "Low", size = 4) + annotate("text", x = 1, y = -0.05, label = "High", size = 4) + theme_classic() + theme(axis.text.x=element_blank(), axis.title.y=element_text(angle = 0), axis.ticks.x=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(), plot.title = element_text(hjust=0.5), axis.line = element_line(arrow = arrow(angle = 15, length = unit(0.15, "inches"), type = "closed")), plot.margin = margin(b = 20, unit = "pt")) # 增加底部边距防止标签截断 print(scenarios_plot) dev.off()
说明
annotate()的x参数设置为0(左端点)和1(右端点),匹配X轴数据的取值范围(0-1)y = -0.05用于将标签定位在X轴下方,可根据实际绘图比例微调该值plot.margin增加底部边距,确保标签不会被输出的图片截断
内容的提问来源于stack exchange,提问作者HelpMe
相关产品推荐
相关产品推荐

