【问题标题】:Adding line breaks between words to axis labels in ggplot在ggplot中将单词之间的换行符添加到轴标签
【发布时间】:2021-09-12 03:19:06
【问题描述】:

我正在寻找一种方法来为我的 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 轴上添加其他能量类型时,我得到一个空白图。

【问题讨论】:

标签: r ggplot2 axis-labels


【解决方案1】:

您可以使用 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')

【讨论】:

  • 非常感谢!这似乎很适合仅绘制数据本身。但是,当我尝试通过 scale_x_discrete(limits 我得到一个空白图。
  • 我认为这是因为当我们使用 stringr::str_wrap(Energy.Type, 10) 时 x 轴值发生了变化,而您的值应该与 str_wrap 中的文本匹配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-16
  • 2021-11-04
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
相关资源
最近更新 更多