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
相关产品推荐
相关产品推荐

