【发布时间】:2019-03-16 14:57:01
【问题描述】:
我正在尝试编写一个函数来在网格中绘制图形。我正在使用 ggplot 和构面网格。我无法通过分面网格的论点。我想知道是否有人能指出我正确的方向。
数据示例:
Year = as.factor(rep(c("01", "02"), each = 4, times = 1))
Group = as.factor(rep(c("G1", "G2"), each = 2, times = 2))
Gender = as.factor(rep(c("Male", "Female"), times = 4))
Percentage = as.integer(c("80","20","50","50","45","55","15","85"))
df1 = data.frame (Year, Group, Gender, Percentage)
不带函数的网格图代码为:
p = ggplot(data=df1, aes(x=Year, y=Percentage, fill = Gender)) + geom_bar(stat = "identity")
p = p + facet_grid(~ Group, scales = 'free')
p
这会产生一个像我想要做的情节。但是,当我把它放到一个函数中时:
MyGridPlot <- function (df, x_axis, y_axis, bar_fill, fgrid){
p = ggplot(data=df1, aes(x=x_axis, y=y_axis, fill = bar_fill)) + geom_bar(stat = "identity")
p = p + facet_grid(~ fgrid, scales = 'free')
return(p)
}
然后运行:
MyGridPlot(df1, df1Year, df1$Percentage, df1$Gender, df1$Group)
出现错误:
Error: At least one layer must contain all faceting variables: `fgrid`.
* Plot is missing `fgrid`
* Layer 1 is missing `fgrid
我尝试过使用aes_string,它适用于 x、y 和填充,但不适用于网格。
MyGridPlot <- function (df, x_axis, y_axis, bar_fill, fgrid){
p = ggplot(data=df1, aes_string(x=x_axis, y=y_axis, fill = bar_fill)) + geom_bar(stat = "identity")
p = p + facet_grid(~ fgrid, scales = 'free')
return(p)
}
然后运行:
MyGridPlot(df1, Year, Percentage, Gender, Group)
这会产生同样的错误。如果我删除构面网格,两个函数代码都运行良好,虽然没有网格:-(
非常感谢您帮助这个初学者。
古斯塔沃
【问题讨论】:
-
一些关于如何使用 tidyeval 和 facets here 的好信息。
-
谢谢!这真的很有帮助。
标签: r function ggplot2 facet facet-grid