r ggplot动态使用plotmath表达式

时间:2017-12-10 22:50:22

标签: 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)

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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