R生成带有空格的标签

Jan*_*erg 3 r

我尝试使用上标生成标签,因此使用parse。我似乎不能使用空格,这有效:

GTVol <- 1:10
measuredVol <- 1:10
dat <- data.frame(GTVol, measuredVol)
ggplot(dat, aes(GTVol, measuredVol)) + 
  geom_point() + 
  geom_abline(slope=1) +
  xlab(parse(text='HarvestedVolume(m^3)')) + 
  ylab("QSM Volume (m^3)")
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

GTVol <- 1:10
measuredVol <- 1:10
dat <- data.frame(GTVol, measuredVol)
ggplot(dat, aes(GTVol, measuredVol)) + 
  geom_point() + 
  geom_abline(slope=1) +
  xlab(parse(text='Harvested Volume (m^3)')) + 
  ylab("QSM Volume (m^3)")
Run Code Online (Sandbox Code Playgroud)

给我以下错误:

Error in parse(text = "Harvested Volume (m^3)") : 
  <text>:1:11: unexpected symbol
1: Harvested Volume
Run Code Online (Sandbox Code Playgroud)

akr*_*run 6

通过添加更改空格字符 ~

library(ggplot2)
ggplot(dat, aes(GTVol, measuredVol)) + 
  geom_point() + 
   geom_abline(slope=1) +
   xlab(parse(text='Harvested~Volume~(m^3)')) + 
   ylab("QSM Volume (m^3)")
Run Code Online (Sandbox Code Playgroud)

-输出

在此处输入图片说明


或者gsub用于动态替换

  ...
   xlab(parse(text=gsub("\\s+", "~", 'Harvested Volume (m^3)'))) + 
   ...
Run Code Online (Sandbox Code Playgroud)

  • @JanHackenberg 很好。我认为 `expression` 或 `bquote` 是正确的方法。我也很困惑你为什么使用 `parse`。 (2认同)
  • 因为我现在只是在空闲时间使用 R,而且这里缺乏专业经验。我想在我的标签中使用上标,并且在搜索解决方案时找到了 parse。现在我两全其美。 (2认同)

Rui*_*das 5

plotmath不需要parse,正确的方法是expression(下面)或bquote

library(ggplot2)


ggplot(dat, aes(GTVol, measuredVol)) + 
  geom_point() + 
  geom_abline(slope = 1) +
  xlab(expression(Harvested ~ Volume ~ (m^3))) + 
  ylab(expression(QSM ~ Volume ~ (m^3)))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明