将单词之间的换行符添加到ggplot中的轴标签

Adding line breaks between words to axis labels in ggplot

我正在寻找一种方法来为我的 x 轴标签添加换行符,因为它们目前太长了。

这是我的几个情节之一的代码:

PortR_plot = ggplot(data=PortR, mapping = aes(x=Energy.Type, y=Scaled.Score, fill=Energy.Type)) 
  + labs(title="Portfolio R", x=('Energy Type'), y=('Scaled Score'))

PortR_plot + geom_boxplot()+ scale_x_discrete(limits=c('Battery storage',
  'Geothermal', 'Onshore Wind','Pumped Storage', 'Run of River Hydro', 'Small Storage Hydro','Solar')) 
  + ylim(0,1)+ theme(text = element_text(size = 20))


我知道您可以使用 scale_x_discrete 添加中断 (\n),但我已经在使用 scale_x_discrete 来显示原始数据集 (PortR) 中没有的空能量类型,因此当我在那里添加换行符时,例如:

scale_x_discrete(limits=c('Battery \n storage','Geothermal', etc etc

它不起作用,因为它与数据集中的能量类型名称不匹配。

我已经尝试 the method from this blog 但没有产生任何明显的变化。

如有任何帮助,我们将不胜感激!

编辑:添加数据样本

structure(list(Project = c("Batt_1", "Wind_2", "Wind_3", "Wind_4", 
"Wind_5", "Wind_6", "Wind_7", "Wind_8", "Wind_9", "Hydro_1", 
"Hydro_2", "Hydro_3"), Energy.Type = c("Battery storage", 
"Onshore Wind", "Onshore Wind", "Onshore Wind", "Onshore Wind", 
"Onshore Wind", "Onshore Wind", "Onshore Wind", "Onshore Wind", 
"Small Storage Hydro", "Small Storage Hydro", "Small Storage Hydro"
), Scaled..T.FW. = c(0, 1.29, 1.19, 0.69, 1.14, 0.11, 0.9, 0.52, 
1.02, 0.85, 0.83, 0.31)), row.names = c(NA, -12L), class = "data.frame")

Edit2:我想我可能在导入 R 之前通过在 excel 中添加一个中断 (alt+enter) 来强制解决方案。仍然有兴趣了解 R 中的解决方案。

Edit3:我尝试按照 Ronak 展示的方法进行操作,但是当我尝试通过 scale_x_discrete(limits) 在 x 轴上添加额外的能量类型时,我得到一个空白图。

您可以使用 stringr::str_wrap 来换行 x 轴文本。您可以根据自己的选择更改 str_wrapwidth 参数。

library(ggplot2)

ggplot(df, aes(x = stringr::str_wrap(Energy.Type, 10), 
               y=Scaled..T.FW., fill=Energy.Type)) +
  geom_boxplot() + 
 labs(title="All Projects", x= 'Energy Type', y= 'Scaled Score')