Jer*_*ryN 5 r ggplot2 plotmath
我想使用 ggplot 动态更改轴标签。下面的代码是我想要做的事情的简单版本。它在 y 轴上正确显示度数符号。注释掉的 ylab 代码行是我想做的但失败了。我想创建绘图代码,将其分配给一个变量(例如 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)
Run Code Online (Sandbox Code Playgroud)
使用bquote
这是你的动态组件
temp <- 12
Run Code Online (Sandbox Code Playgroud)
使用将其分配给标签
ylab(bquote(Temperature ~is ~ .(temp) ~(degree~F)))
Run Code Online (Sandbox Code Playgroud)
或者在下面解决您的其他问题
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)))
Run Code Online (Sandbox Code Playgroud)