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

ggplot2中geom_text是否有orientation="y"的替代方案?

解决ggplot2水平堆叠条形图标签对齐问题

因为geom_text没有orientation参数,直接用position_stack()会按垂直条形的逻辑计算位置,导致标签和水平堆叠的条形无法对齐。这里提供两种替代方案:

方案一:手动计算标签中点位置

先通过数据处理计算每个堆叠部分的x轴中点,直接定位标签位置,避免依赖position_stack的默认行为:

library(ggplot2)
library(dplyr)

dat <- data.frame(
  y = rep(1:2, each = 2),
  x = c(.2, .8, .8, .2),
  fill = rep(c("A", "B"))
)

# 按y分组计算每个堆叠部分的x中点
dat <- dat %>%
  group_by(y) %>%
  arrange(fill) %>% # 确保顺序与条形堆叠顺序一致
  mutate(cum_x = cumsum(x) - x/2) %>% # 计算中点位置
  ungroup()

ggplot(dat, aes(x, y, fill = fill)) +
  geom_col(orientation = "y") +
  scale_y_continuous(
    breaks = 1:2, labels = c("a", "b"), 
    sec.axis = dup_axis(labels = c("n = 100", "n = 50"))) +
  geom_text(aes(x = cum_x, label = x), hjust = .5) # 用计算好的中点定位

方案二:调整position_stack与文本对齐参数

无需修改原始数据,通过调整geom_text的hjust参数和position_stack的设置,让标签自动对齐:

library(ggplot2)

dat <- data.frame(
  y = rep(1:2, each = 2),
  x = c(.2, .8, .8, .2),
  fill = rep(c("A", "B"))
)

ggplot(dat, aes(x, y, fill = fill)) +
  geom_col(orientation = "y") +
  scale_y_continuous(
    breaks = 1:2, labels = c("a", "b"), 
    sec.axis = dup_axis(labels = c("n = 100", "n = 50"))) +
  geom_text(aes(label = x),
    position = position_stack(vjust = .5), # 控制垂直方向居中
    hjust = .5 # 控制水平方向居中
  )

两种方案都能让标签准确落在每个堆叠条形的中间,且不需要使用coord_flip()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:27:45