2

我正在尝试编写一个使用 ggplot 但允许用户指定几个绘图变量的函数。但是我无法让它作为一个函数工作(收到错误消息:见下文)。

下面提供了一个小的示例数据集和工作实现,以及我对该函数的尝试和相关的错误。我确定这与非标准评估(NSE)有关,但鉴于我在函数中使用了过滤器,我不确定如何解决它,而且我的各种尝试都是徒劳的。

library(dplyr)
library(ggplot2)

df<-data.frame(Date=c(seq(1:50),seq(1:50)), SRI=runif(100,-2,2), SITE=(c(rep("A",50), rep("B", 50))))

ggplot() +
geom_linerange(aes(x = Date, ymin = 0, ymax = SRI), colour = I('blue'), data = filter(df, SRI>0)) +
geom_linerange(aes(x = Date, ymin = SRI, ymax = 0), colour = I('red'), data = filter(df, SRI<=0)) +
facet_wrap(~SITE) +
labs(x = 'Date', y = "yvar", title = "Plot title")

上面的工作,但是当作为一个函数实现时:

plot_fun <- function(df, x, y, ylab="y-lab", plot_title="Title", facets) {
ggplot() +
geom_linerange(aes(x = x, ymin = 0, ymax = y), colour = I('blue'), data = filter(df, y > 0)) +
geom_linerange(aes(x = x, ymin = y, ymax = 0), colour = I('red'), data = filter(df, y <= 0)) +
facet_wrap(~ facets) +
labs(x = 'Date', y = ylab, title = plot_title)
return(p)
}

plot_fun(df, x="Date", y="SRI", ylab="y-lab", plot_title="Title", facets="SITE")

我收到以下“错误:美学必须是长度 1 或与数据 (1) 相同:x、ymin、max”。

我尝试了各种使用as_stringand的方法filter_,但都没有成功。

非常感谢任何帮助。

问候

缺口

4

1 回答 1

2

您需要aes_string按预期切换并更改facet_wrap代码以将facets参数作为公式或删除波浪号,如该问题的答案中所示。您还需要切换到 using filter_,它可以与interpfrom package lazyeval一起使用。

library(lazyeval)

这是您的功能,其中包含我概述的更改和结果图:

plot_fun <- function(df, x, y, ylab = "y-lab", plot_title = "Title", facets) {
    ggplot() +
        geom_linerange(aes_string(x = x, ymin = 0, ymax = y), colour = I('blue'), 
                    data = filter_(df, interp(~var > 0, var = as.name(y)))) +
        geom_linerange(aes_string(x = x, ymin = y, ymax = 0), colour = I('red'), 
                    data = filter_(df, interp(~var <= 0, var = as.name(y)))) +
        facet_wrap(facets) +
        labs(x = 'Date', y = ylab, title = plot_title)
}

plot_fun(df, x="Date", y="SRI", facets="SITE")

在此处输入图像描述

于 2015-11-06T00:04:27.067 回答