r - 如何从变量传递 ggplot2 美学?

标签 r ggplot2

我无法将存储在变量中的 POSIXct 作为 geom_rect 的 xmin/xmax 传递。我试图构建一个独立的示例,而不会轻视我正在尝试做的事情......

这个想法是采用一个 ggplot2 绘图对象,其 x 是一个 POSIXt,并在特定时间范围内“放大”。缩放位于顶部 80%,整个系列位于底部 20%,并带有指示哪个部分在顶部缩放。

我的问题是我似乎无法将 xmin/xmax 传递给 geom_rect - 我尝试过的每件事(除了手动组装绘图而不是函数)都给了我一个不同的错误。我尝试过使用 aes()、aes_string()、作为参数而不是美学传递、只传递字符串等。

下面的例子告诉我:

Error in eval(expr, envir, enclos) : object 'lims' not found

我认为我的问题是,当美学得到处理时,我用来设置美学的变量不在范围内,但我不知道如何去做。帮助。
library(ggplot2)

subplot <- function(x, y) viewport(layout.pos.col=x, layout.pos.row=y)
vplayout <- function(x, y) {
  grid.newpage()
  pushViewport(viewport(layout=grid.layout(y,x)))
}

anm_zoom <- function(limits, p) {

  lims <- as.POSIXct(limits)
  limlab <- paste(lims, collapse=" to ")

  top <- p + scale_x_datetime(limlab, limits=lims, expand=c(0,0))

  bottom <- p;
  bottom <- bottom + opts(title="")
  bottom <- bottom + opts(legend.position="none")
  bottom <- bottom + opts(axis.title.y=theme_blank())
  bottom <- bottom + scale_x_datetime("", expand=c(0,0))
  bottom <- bottom + geom_rect(aes(xmin=lims[1], xmax=lims[2]),
 ymin=-Inf, ymax=Inf, fill="grey80", alpha=0.01)

  ## Render the plots
  vplayout(1,5)
  print(top, vp=subplot(1,c(1,2,3,4)))
  print(bottom, vp=subplot(1,5))
}


pdate <- seq.POSIXt(from=as.POSIXct("2010-09-09 00:00"),
   to=as.POSIXct("2010-09-10 23:59"), by="2 mins")
var1 <- rnorm(length(pdate))
var2 <- rnorm(length(pdate))
df1 <- data.frame(pdate, var1, var2)

dm  <- melt(df1, id="pdate")

p <- ggplot(dm) + aes(x=pdate, y=value) + stat_summary(fun.y="sum", geom="line")

anm_zoom(c("2010-09-09 12:15", "2010-09-09 12:30"), p)

最佳答案

嗯,我想你需要一个新的 aes有点像aes的函数(因为它不尝试解析它的参数)有点像 aes_string (因为它立即在本地环境中评估其参数):

aes_now <- function(...) {
  structure(list(...),  class = "uneval")
}

然后
bottom <- bottom + geom_rect(aes_now(xmin=lims[1], xmax=lims[2]),
 ymin=-Inf, ymax=Inf, fill="grey80", alpha=0.01)

给你你想要的。

关于r - 如何从变量传递 ggplot2 美学?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3737619/

相关文章:

r - 无法为并行集群打开套接字

R- Optimx 用于具有 2 个参数的指数函数 - 无法在初始参数值处评估函数

r - ggplot2 带有空格和 tidyeval 语法的变量名

使用 ggplot2 从 geom_rect 中删除边框

r - 在 R Shiny 中渲染时如何将表格单元格扩展到多列?

r - 我在哪里可以找到 SEC XBRL 财务数据的确切链接以便将它们下载到 R 中?

r - Anova 表比较组,在 R 中,导出到 latex ?

r - 如何控制ggplot中轴线的长度?

r - 离散与连续情况下的映射与设置颜色

r - 需要在 ggplot2 中使用 viridis 进行特定着色