r ggplot动态使用plotmath表达式

r ggplot动态使用plotmath表达式,r,ggplot2,plotmath,R,Ggplot2,Plotmath,我想使用ggplot动态更改轴标签。下面的代码是我想做的简单版本。它在y轴上正确地显示了一个度符号。注释掉的ylab代码行是我想做的,但失败了。我想创建plotmath代码,将其分配给变量(例如yLabel),然后让ggplot解释它 library(data.table) library(ggplot2) DT <- data.table(timeStamp=c(1:12), ColN1=runif(12, 0, 10)) DT.long <- data.table::melt(

我想使用ggplot动态更改轴标签。下面的代码是我想做的简单版本。它在y轴上正确地显示了一个度符号。注释掉的ylab代码行是我想做的,但失败了。我想创建plotmath代码,将其分配给变量(例如yLabel),然后让ggplot解释它

library(data.table)
library(ggplot2)

DT <- data.table(timeStamp=c(1:12), ColN1=runif(12, 0, 10))
DT.long <- data.table::melt(
  DT, id.vars = c("timeStamp"))

yLabel <- "Temperature~(~degree~F)"
yLabel1 <- expression("Temperature~(~degree~F)")

p <- ggplot(data = DT.long, aes(x = timeStamp, y = value)) + 
  xlab("Time") + 
  #    ylab( expression(paste("Value is ", yLabel,","))) +
#  ylab(yLabel) +
#  ylab(yLabel1) +
  ylab(Temperature~(~degree~F)) +

    scale_y_continuous() +
  theme_bw() +
  geom_line()
print(p)
库(data.table)
图书馆(GG2)

DT使用
bquote

这是您的动态组件

temp <- 12
或者回答下面的附加问题

V = "Temperature is ("~degree~"F)"
W = "depth is ("~degree~"C)"

ggplot(data = DT.long, aes(x = timeStamp, y = value)) + 
  xlab("Time") +
  ylab(bquote(.(V)))

ggplot(data = DT.long, aes(x = timeStamp, y = value)) + 
  xlab("Time") +
  ylab(bquote(.(W)))

我在动态修改axis标签时遇到了同样的问题,B Williams的回答帮助了我

解决方案:

dynamic <- "dynamic text"

# Put the dynamic text in its right context
str <- sprintf("Static label text [%s]", dynamic)

# Use multiplication "*" rather than "~" to build the expression to avoid unnecessary space 
complete_label <- bquote(.(str)[subscript]*"/L")

这不管用。我想将“温度是…”赋值给一个变量(比如V),然后使用ylab(V)。我尝试了
ylab(bquote(.V)
,但没有成功。
dynamic <- "dynamic text"

# Put the dynamic text in its right context
str <- sprintf("Static label text [%s]", dynamic)

# Use multiplication "*" rather than "~" to build the expression to avoid unnecessary space 
complete_label <- bquote(.(str)[subscript]*"/L")
library(ggplot2)
ggplot() + labs(x = complete_label)