r ggplot 动态使用 plotmath 表达式

r ggplot use plotmath expressions dynamically

我想使用 ggplot 动态更改轴标签。下面的代码是我想做的事情的简单版本。它在 y axis.The 中正确显示度数符号,注释掉 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)

使用bquote

这是您的动态组件

temp <- 12

使用

将其分配给标签
ylab(bquote(Temperature ~is ~ .(temp) ~(degree~F)))

或在下面解决您的其他问题

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)))

我在动态修改轴标签时遇到了同样的问题,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")

验证它是否有效:

library(ggplot2)
ggplot() + labs(x = complete_label)