r ggplot 动态使用 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(
  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)))

关于r ggplot 动态使用 plotmath 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47744333/

相关文章:

r - 将字符串向量连接成一个字符串 - 对于 df 中的每一行

r - 仅当向量为 '>0' 时,如何对列求和?

r - 使用另一个 data.frame 的列对 data.frame 进行排序

r - 可以交互使用包,但 Rscript 给出错误

R:plotmath 表达式符号未显示在交互图中

r - map 轴标签中的度数符号不正确

ggplot、ggridges 中的倒序

r - 当绘图背景透明时,plot(p)和plot(ggplot_gtable(ggplot_build(p)))似乎没有给出相同的输出

R : confidence interval being partially displayed with ggplot2 (using geom_smooth())

r - 如何在R中的plotmath中写远小于符号(<<)?