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

如何将ggplot2图表的Y轴标签移至绘图区域内部?

将Y轴国家标签移至绘图区域内部的实现方法

解决方案思路

隐藏原生Y轴的标签、刻度和标题,使用geom_text在绘图区域内的指定位置(x=0虚线附近)添加国家名称作为自定义标签。

完整代码

首先是数据定义:

df <- structure(list(country = c("Italy", "Switzerland", "Sweden", 
                       "Netherlands", "England", "Poland", "Russia", "Czech", "Hungary", 
                       "Turkey"), `0.025quant` = c(-2.98, 2.02, 1.02, 0.02, 3.02, -2.98, 
                                                   -0.98, -1.98, -1.98, -0.98), mean = c(-2, 3, 2, 1, 4, -2, 0, 
                                                                                         -1, -1, 0), `0.975quant` = c(-1.02, 3.98, 2.98, 1.98, 4.98, -1.02, 
                                                                                                                      0.98, -0.02, -0.02, 0.98)), class = c("tbl_df", "tbl", "data.frame"
                                                                                                                      ), row.names = c(NA, -10L))

修改后的绘图代码:

plot <- ggplot(data = df, aes(x = mean, y = country)) + 
  geom_point() + 
  geom_errorbarh(aes(xmin = `0.025quant`, xmax = `0.975quant`), height = .1) + 
  geom_vline(xintercept = 0, linetype = 2) + 
  # 在x=0左侧添加国家标签,可调整x值改变位置
  geom_text(aes(x = -0.2, label = country), hjust = 1, size = 3.5) + 
  scale_x_continuous(breaks = seq(-3, 5, 1)) + 
  # 隐藏原生Y轴元素
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        axis.title.y = element_blank())

print(plot)

关键细节说明

  • geom_text的x参数可按需调整:若想把标签放在x=0虚线右侧,可将x设为0.2,同时把hjust改为0实现左对齐
  • size参数控制标签文字大小,可根据图表尺寸调整
  • theme中的设置彻底隐藏原生Y轴的所有元素,避免和自定义标签冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 09:16:12