将参数添加到ggplot生成的函数图中

时间:2015-08-21 10:21:30

标签: r ggplot2

假设我有一个名为my_plot的已保存的情节,使用ggplot制作。另外,假设用于水平轴的my_plot[[1]]数据框中的列名为my_dates

现在,我想在情节中添加一些垂直线条,当然,这可以通过以下方式完成:

my_plot + 
    geom_vline(aes(xintercept = my_dates[c(3, 8)]))

由于我经常执行此任务,我想为此编写一个函数 - 类似的东西:

ggplot.add_lines <- function(given_plot, given_points) {
    finale <- given_plot + 
        geom_vline(aes(xintercept = given_plot[[1]]$my_dates[given_points]))
    return(finale)
}

对于每个人来说,这可能是显而易见的,但是不起作用:

> ggplot.add_lines(my_plot, c(3, 5))
Error in eval(expr, envir, enclos) : object 'given_plot' not found

所以,我的问题是我做错了什么,怎么解决?以下是可重现示例的一些数据:

> dput(my_plot)
structure(list(data = structure(list(my_dates = c(1, 2, 3, 4, 
5, 6, 7, 8, 9, 10), my_points = c(-2.20176409422924, -1.12872396340683, 
-0.259703895194354, 0.634233385649338, -0.678983982973015, -1.83157126614836, 
1.33360095418957, -0.120455389285709, -0.969431974863616, -1.20451262626184
)), .Names = c("my_dates", "my_points"), row.names = c(NA, -10L
), class = "data.frame"), layers = list(<environment>), scales = <S4 object of class structure("Scales", package = "ggplot2")>, 
mapping = structure(list(x = my_dates, y = my_points), .Names = c("x", 
"y"), class = "uneval"), theme = list(), coordinates = structure(list(
    limits = structure(list(x = NULL, y = NULL), .Names = c("x", 
    "y"))), .Names = "limits", class = c("cartesian", "coord"
)), facet = structure(list(shrink = TRUE), .Names = "shrink", class = c("null", 
"facet")), plot_env = <environment>, labels = structure(list(
    x = "my_dates", y = "my_points"), .Names = c("x", "y"
))), .Names = c("data", "layers", "scales", "mapping", "theme", 
"coordinates", "facet", "plot_env", "labels"), class = c("gg", 
"ggplot"))

2 个答案:

答案 0 :(得分:2)

根据this post,以下是我对此问题的解决方案。 ** ply和ggplot中的环境问题很烦人。

ggplot.add_lines <- function(given_plot, given_points) {
    finale <- eval(substitute( expr = {given_plot + 
        geom_vline(aes(xintercept = my_dates[given_points]))}, env = list(given_points = given_points)))
    return(finale)
}

以下代码在我的机器上运行良好。 (我无法在我的机器上重复工作......)

df <- data.frame(my_dates = 1:10, val = 1:10)
my_plot <- ggplot(df, aes(x = my_dates, y = val)) + geom_line()
my_plot <- ggplot.add_lines(my_plot, c(3, 5))
print(my_plot)

更新:当使用两个以上的点时,上述解决方案会失败。​​

似乎我们可以通过不包括aes(子集与aes导致问题)轻松解决此问题:

ggplot.add_lines <- function(given_plot, given_points) {        
    finale <- given_plot + geom_vline(xintercept = given_plot[[1]]$my_dates[given_points])
    return(finale)
}

enter image description here

答案 1 :(得分:1)

我会采用以下方法:提取感兴趣的data.frame,并将其传递给新层,

df <- data.frame(my_dates = 1:10, val = rnorm(10))
my_plot <- ggplot(df, aes(x = my_dates, y = val)) + geom_line()

add_lines <- function(p, given_points=c(3,5), ...){
  d <- p[["data"]][given_points,]
  p + geom_vline(data = d, aes_string(xintercept="my_dates"), ...)
}

add_lines(my_plot, c(3,5), lty=2)

enter image description here