如何修改ggplot2的坐标轴刻度标签以避免内容重复
解决方法
你可以通过修改刻度标签+添加底部统一注释的方式实现需求,具体修改后的代码如下:
library(ggplot2) library(ggpubr) # 对应你用到的theme_pubr trainingplot <- ggplot(sample_descriptive, aes(x=trainingblock, y=pointEstimate)) + theme_pubr() + scale_y_continuous(name = "直线滑翔时间扣除量(秒)", limits = c(-1, 5), breaks = c(-1, 0, 1, 2,3,4)) + # 修改x轴刻度标签,仅保留序号和首尾分类 scale_x_discrete(expand = expansion(add = c(.6, 1.2)), labels= c("前测", "1", "2", "3", "保留测试(72小时)")) + annotate("text", x = 5.5, y = -0.4, label = "路线A", size=4.5) + annotate("text", x = 5.5, y = 0.5, label = "路线B", size=4.5) + annotate("text", x = 5.5, y = 2, label = "路线C", size=4.5) trainingplot <- trainingplot + geom_errorbar(data = sample_descriptive, aes(x=trainingblock, y = pointEstimate, ymin = lower.CL,ymax = upper.CL, group=interaction(course, group)), position = position_dodge(0.2), size=1, width=0.3) + geom_line(data = sample_descriptive, aes(x=trainingblock, y = pointEstimate, group=interaction(course, group)), position = position_dodge(0.2), alpha=0.4) + geom_point(data = sample_descriptive, aes(x=trainingblock, y=pointEstimate, shape=group, fill=group, group=interaction(course, group)), position = position_dodge(0.2), size=2.8, color="black") + geom_hline(aes(yintercept = 0), linetype = "dashed", size=0.2) + scale_fill_manual(values = c("#1A85FF", "#D41159", "#FFB000")) + scale_shape_manual(values=c(21, 24)) + # 调整主题配置:关闭x轴标题、增加底部边距放统一标签 theme(legend.position="none", axis.title.x=element_blank(), plot.margin = unit(c(0.5,1,2,0.5), "lines")) + # 添加统一的练习块标注,关闭裁剪避免文字被切掉 annotate("text", x = 3, y = -1.4, label = "习得试次块", size = 4) + coord_cartesian(ylim = c(-1,5), clip = "off")
核心改动说明
- 修改了
scale_x_discrete的labels参数,把重复的前缀文本删除,仅保留1、2、3作为刻度显示 - 调整了
plot.margin给底部留出足够空间放置统一分类文本,四个参数依次对应上、右、下、左的边距,单位为行 - 新增
annotate在三个序号刻度的居中位置添加统一标注,如果标注的上下位置不符合需求,直接调整y参数的数值即可,数值越小位置越靠下 - 新增
coord_cartesian关闭坐标轴裁剪,确保底部超出绘图区域的文本可以正常显示 - 已将原有英文的标签、轴标题翻译为中文,如果你需要保留英文版本,把对应的label值改回原英文即可。
内容的提问来源于stack exchange,提问作者Cmagelssen
相关产品推荐
相关产品推荐

