R ggplot dynamically uses graphical expressions

I want to dynamically change axis labels with ggplot. The code below is a simple version of what I would like to do. It correctly displays the degree symbol on the y axis. Commented out lines of ylab code is what I would like to do but fail. I want to create plotmath code, assign it to a variable (e.g. yLabel), and then ggplot interpret it.

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)
+4
source share
1 answer

Use bquote

Here is your dynamic component

temp <- 12

Assign it to a tag using

ylab(bquote(Temperature ~is ~ .(temp) ~(degree~F)))

Or contact your further question below.

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)))
+2
source

Source: https://habr.com/ru/post/1690530/


All Articles