如何在ggplot2的scale_fill_discrete()函数中实现标签换行?
在ggplot的scale_fill_discrete标签中实现换行效果
你可以通过两种方式给scale_fill_discrete()里的标签添加换行:
方法1:手动插入换行符\n
直接在标签字符串中用\n指定需要换行的位置,ggplot会自动识别并拆分文本:
scale_fill_discrete(labels=c( "Is an inherited disorder,\nhaving genetic basis", "Due to\ndietary deficiency", "Term is known but\ndon’t know the etiology", "Completely unknown" ))
方法2:用stringr::str_wrap自动换行
如果不想手动控制换行位置,可以借助stringr包的str_wrap()函数,根据指定宽度自动拆分长文本。需要先加载stringr包:
library(stringr) scale_fill_discrete(labels=str_wrap(c( "Is an inherited disorder, having genetic basis", "Due to dietary deficiency", "Term is known but don’t know the etiology", "Completely unknown" ), width = 20)) # 可根据需求调整width参数的数值
完整修改示例
结合你的代码,调整后的完整代码如下(两种方法二选一即可):
library(ggplot2) library(stringr) # 使用自动换行方法时需要加载 ggplot(dat, aes(x= What_is_NMD, group=Gender, fill = What_is_NMD)) + geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") + geom_text(aes(label = scales::percent(..prop.., accuracy = 0.01), y= ..prop.. ), stat= "count", vjust = -.5) + labs(x="What is NMD?", y = "Percent", fill="What is NMD?") + facet_grid(~Gender) + scale_y_continuous(labels = scales::percent)+ theme(axis.text.x = element_blank(), axis.ticks.x=element_blank(), legend.key.height=unit(1.5, "cm")) + # 适当调高图例高度适配换行标签 # 手动换行写法 scale_fill_discrete(labels=c( "Is an inherited disorder,\nhaving genetic basis", "Due to\ndietary deficiency", "Term is known but\ndon’t know the etiology", "Completely unknown" )) # 自动换行写法(替换上面的手动换行代码即可) # scale_fill_discrete(labels=str_wrap(c( # "Is an inherited disorder, having genetic basis", # "Due to dietary deficiency", # "Term is known but don’t know the etiology", # "Completely unknown" # ), width = 20))
另外注意:你原代码中fill = str_wrap(What_is_NMD)可以简化为fill = What_is_NMD,因为我们已经在scale_fill_discrete里单独设置了标签的换行,无需提前处理映射变量。
内容的提问来源于stack exchange,提问作者user149054
相关产品推荐
相关产品推荐

