我正在尝试编写一个在网格中绘制图形的函数。我正在使用ggplot和facet网格。我无法通过方面网格的论点。我想知道是否有人可以指出我正确的方向。
数据示例:
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)
这将产生相同的错误。如果我删除构面网格,尽管没有网格:-(
非常感谢您对初学者的帮助。
古斯塔沃
答案 0 :(得分:1)
您的问题是,在函数中,ggplot正在寻找变量名(x_axis
,y_axis
等),但您却给它对象(df1$year
...) 。
有几种方法可以解决这个问题。也许最简单的方法是重写该函数,以便它可以包含对象。例如:
MyGridPlot <- function(x_axis, y_axis, bar_fill, fgrid){ # Note no df parameter here
df1 <- data.frame(x_axis = x_axis, y_axis = y_axis, bar_fill = bar_fill, fgrid = fgrid) # Create a data frame from inputs
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(Year, Percentage, Gender, Group)
或者,您可以使用数据框和变量名来设置函数。如果您按照此处的方式使用单个对象,则没有太多理由这样做,但是如果使用数据框,则可能会使您的生活更轻松:
MyGridPlot <- function(df, x_var, y_var, fill_var, grid_var){
# Need to "tell" R to treat parameters as variable names.
df <- df %>% mutate(x_var = UQ(enquo(x_var)), y_var = UQ(enquo(y_var)), fill_var = UQ(enquo(fill_var)), grid_var = UQ(enquo(grid_var)))
p = ggplot(data = df, aes(x = x_var, y = y_var, fill = fill_var)) + geom_bar(stat = "identity")
p = p + facet_grid(~grid_var, scales = 'free')
return(p)
}
MyGridPlot(df1, Year, Percentage, Gender, Group)