【问题标题】:Error in trying to write a plotting function in ggplot2尝试在 ggplot2 中编写绘图函数时出错
【发布时间】:2014-10-02 09:30:49
【问题描述】:

我正在尝试在 ggplot2 中编写一个函数并获取此错误消息:

layout_base 中的错误(数据、变量、drop = drop):
至少一层必须包含用于分面的所有变量

这是我的代码:

growth.plot<-function(data,x,y,fac){ 
gp <- ggplot(data = data,aes(x = x, y = y)) 
gp <- gp + geom_point()  + facet_wrap(~ fac)
return(gp)
}

growth.plot(data=mydata, x=x.var, y=y.var,fac= fac.var)

如果我尝试不使用该功能,则情节会完美显示

gp1 <- ggplot(data = mydata,aes(x = x.var), y = y.var))
gp1+ geom_point()+ facet_wrap(~ fac.var) # this works

【问题讨论】:

  • 看看aes_string
  • 谢谢,我试过了,可惜没用。
  • 我认为this answer 可能是您要找的。​​span>

标签: r function ggplot2


【解决方案1】:

这是可重现的解决方案,其中您的 x、y 和 fac 参数必须作为字符传递:

library(ggplot2)

make_plot = function(data, x, y, fac) {
    p = ggplot(data, aes_string(x=x, y=y, colour=fac)) +
        geom_point(size=3) +
        facet_wrap(as.formula(paste("~", fac)))
    return(p)
}

p = make_plot(iris, x="Sepal.Length", y="Petal.Length", fac="Species")

ggsave("iris_plot.png", plot=p, height=4, width=8, dpi=120)

感谢评论者 @Roland 和 @aosmith 指出解决方案的方法。

【讨论】:

  • 非常感谢,它运行良好。很难通过小的 R 微妙之处找到它的方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 2019-05-06
相关资源
最近更新 更多