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

ggplot绘图中出现stringr::str_wrap代码字样的问题求助

解决ggplot x轴标签显示stringr::str_wrap(Age.Group,15)的问题

问题成因

你把stringr::str_wrap(Age.Group,15)直接写在aes(x=...)里了,ggplot会把这个完整表达式当成x轴的轴标题显示,而不是自动执行文本换行来生成刻度标签。

两种解决方案

方案1:提前处理数据集(推荐,适合后续复用)

先把两个数据集中的Age.Group列做换行处理,再传入ggplot绘图:

# 处理第一个数据集的Age.Group列
EDDisWiderAllSexes <- EDDisWiderAllSexes %>%
  mutate(Age.Group = stringr::str_wrap(Age.Group, 15))

# 处理第二个数据集的Age.Group列
StateDisWiderAllSexes <- StateDisWiderAllSexes %>%
  mutate(Age.Group = stringr::str_wrap(Age.Group, 15))

# 绘制图表,直接用处理后的列
DisPlot <- ggplot() +
  geom_bar(data = EDDisWiderAllSexes, aes(x = Age.Group, y = `Population with a disability as a percentage`, fill = "Electoral Division"), width= 0.4, 
           position = position_nudge(0.22), stat = "identity") +
  geom_bar(data = StateDisWiderAllSexes, aes(x = Age.Group, y = `Population with a disability as a percentage`, fill = "Ireland"), width= 0.4,
           position = position_nudge(-0.22), stat = "identity") +
  labs(fill = "Legend") +
  theme(axis.text.x = element_text(angle = 0))+
 coord_fixed(1/20)

方案2:绘图时临时处理刻度标签(不修改原始数据)

在scale_x_discrete里指定标签的处理逻辑,仅在绘图生效:

DisPlot <- ggplot() +
  geom_bar(data = EDDisWiderAllSexes, aes(x = Age.Group, y = `Population with a disability as a percentage`, fill = "Electoral Division"), width= 0.4, 
           position = position_nudge(0.22), stat = "identity") +
  geom_bar(data = StateDisWiderAllSexes, aes(x = Age.Group, y = `Population with a disability as a percentage`, fill = "Ireland"), width= 0.4,
           position = position_nudge(-0.22), stat = "identity") +
  labs(fill = "Legend") +
  # 在这里设置x轴刻度的换行逻辑
  scale_x_discrete(labels = function(x) stringr::str_wrap(x, 15)) +
  theme(axis.text.x = element_text(angle = 0))+
 coord_fixed(1/20)

方法区别

  • 方案1修改了原始数据集的列,适合需要多次使用换行后标签的场景;
  • 方案2仅在绘图时临时处理,不会改变原始数据结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 12:32:22