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

如何在R ggplot2镜像图中将年龄轴放置于红蓝色块中间

解决方案

你要实现的是将年龄刻度放在正负值的中间分割线上,只需要关闭默认的纵轴(翻转后的age轴),手动在y=0位置添加轴线、刻度和标签即可,具体实现代码如下:

library(ggplot2)

# 定义年龄刻度和标签
age_brks <- seq(15, 75, 5)
age_labs <- c(paste0(seq(15,70,5)), "75 ou +")

ggplot(test,
       aes(x = age,
           y = agriculteurs_exploitants,
           fill = sexe)) +
  geom_area() +
  geom_line(aes(y = ensemble_des_personnes_en_emploi)) +
  # 添加中间分割轴线
  geom_hline(yintercept = 0, linewidth = 0.3) +
  # 添加年龄刻度线
  geom_segment(data = data.frame(x = age_brks),
               aes(x = x, xend = x, y = -0.1, yend = 0.1),
               inherit.aes = F, linewidth = 0.3) +
  # 添加年龄标签
  annotate("text", x = age_brks, y = 0, label = age_labs, size = 3) +
  scale_y_continuous(limits = c(-3,3),
                     breaks = c(-3,-2,-1,0,1,2,3),
                     labels = c("3","2","1","0","1","2","3")) +
  # 关闭默认的age轴显示
  scale_x_continuous(breaks = NULL) +
  coord_flip() +
  theme_minimal() +
  theme(
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.title.y = element_blank()
  )

运行上述代码后,年龄刻度就会准确显示在红蓝两个色块的中间分割线上。如果需要调整标签的位置、大小或者刻度线的长度,修改对应参数即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:12:00