【问题标题】:r ggplot use plotmath expressions dynamicallyr ggplot 动态使用 plotmath 表达式
【发布时间】:2018-05-24 11:15:06
【问题描述】:

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

【问题讨论】:

    标签: r ggplot2 plotmath


    【解决方案1】:

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

    【讨论】:

    • 这不起作用。我想将“温度是......”分配给一个变量(比如V),然后使用ylab(V)。我试过ylab(bquote(.V)。那没用。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-05-06
      • 2021-02-20
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 2013-01-08
      • 2014-05-05
      相关资源
      最近更新 更多