在Hadley Wickham的《ggplot2》一书的第10.3章中,他提到了制作绘图函数。我想制作许多使用刻面的类似图,但我不能引用专栏。如果我所有的参考文献都是美学方面的,那么我就可以使用aes_string,一切都可以正常工作。Facet_wrap似乎没有类似的东西。
library(ggplot2)
data(iris)
这是我想要函数化的图。
pl.flower1 <- ggplot(data=iris,
aes_string(x='Sepal.Length', y='Sepal.Width', color='Petal.Length')) +
geom_point() +facet_wrap(~Species)
如果我不刻面,这是可行的。
flowerPlot <- function(dat, sl, sw, pl, sp){
ggplot(data=dat, aes_string(x=sl, y=sw, color=pl)) + geom_point()
}
pl.flower2 <- flowerPlot(iris, sl='Sepal.Length', sw='Sepal.Width', pl='Petal.Length')
下面两行中的"sp“应该是什么?一个公式,一个字符串?也许整个方法都是错的。
flowerPlotWrap <- function(dat, sl, sw, pl, sp){
ggplot(data=dat, aes_string(x=sl, y=sw, color=pl)) + geom_point() +facet_wrap(sp)
}
pl.flower3 <- flowerPlotWrap(iris, sl='Sepal.Length', sw='Sepal.Width', pl='Petal.Length', sp= ?????)
除了一个答案之外,我还想指出人们是如何处理这个问题的?
发布于 2012-04-04 12:29:02
facet_wrap
需要一个公式作为它的第一个参数,所以我用as.formula
强制它,并以字符串的形式输入我的sp
:
flowerPlotWrap <- function(dat, sl, sw, pl, sp){
ggplot(data=dat, aes_string(x=sl, y=sw, color=pl)) +
geom_point() +facet_wrap(as.formula(sp)) # note the as.formula
}
pl.flower3 <- flowerPlotWrap(iris, sl='Sepal.Length',
sw='Sepal.Width', pl='Petal.Length',
sp= '~Species')
或者,如果我的公式总是看起来像~[columnname]
,我可以将其构建到flowerPlotWrap
中,并传入列名:
flowerPlotWrap <- function(dat, sl, sw, pl, sp){
ggplot(data=dat, aes_string(x=sl, y=sw, color=pl)) +
geom_point() +facet_wrap(as.formula(sprintf('~%s',sp)))
}
pl.flower3 <- flowerPlotWrap(iris, sl='Sepal.Length',
sw='Sepal.Width', pl='Petal.Length',
sp= 'Species')
(感谢您问题中的可重现示例!如果每个人都像这样问问题,他们会更快地得到答案)。
发布于 2018-11-06 17:42:19
以下是使用ggplot2 V3.0.0
新功能的一些替代方案
使用字符串:
flowerPlot <- function(dat, sl, sw, pl, sp){
ggplot(data=dat, aes(x=!!ensym(sl), y=!!ensym(sw), color=!!ensym(pl))) +
geom_point() +
facet_wrap(eval(expr(~!!ensym(sp))))
}
flowerPlot(iris, sl='Sepal.Length', sw='Sepal.Width', pl='Petal.Length', sp = 'Species')
使用名称:
flowerPlot2 <- function(dat, sl, sw, pl, sp){
ggplot(data=dat, aes(x=!!enquo(sl), y=!!enquo(sw), color=!!enquo(pl))) +
geom_point() +
facet_wrap(eval(expr(~!!enquo(sp))))
}
flowerPlot2(iris, sl= Sepal.Length, sw=Sepal.Width, pl=Petal.Length, sp = Species)
发布于 2012-04-04 12:28:43
如果我只使用sp='Species'
,也就是你想用来刻面的变量的名称,那么你的函数在我没有修改的情况下工作得很好。
flowerPlotWrap(iris, sl='Sepal.Length', sw='Sepal.Width', pl='Petal.Length', sp='Species')
https://stackoverflow.com/questions/10004847
复制相似问题