Reputation: 107
I referred some articles of passing function as an argument and I hope I could then produce plots with different themes by using ggplot2. The following 2 functions could plot correctly:
# plot data
dat <- diamonds[sample(1:nrow(diamonds), 5000), ]
gplot1 <- function(FUN = theme_bw) {
ggplot(dat, aes(carat, price))+
geom_point(aes(colour = color))+
FUN()
}
gplot1(theme_gray)
gplot2 <- function(FUN) {
theme_set(FUN)
ggplot(dat, aes(carat, price))+
geom_point(aes(colour = color))
}
gplot2(theme_bw())
But how could I plot with different themes by one function call? I tried gplot1() and got nothing, while I tried gplot2() I got warning messages and without any plot:
themes1 <- c(theme_bw, theme_gray)
for(i in themes1) gplot1(i)
# nothing
themes2 <- c(theme_bw(), theme_gray())
for(i in themes2) gplot2(i)
# warning messages and without any plot
Could anyone enlighten me? Thanks a lot!
Upvotes: 3
Views: 304
Reputation: 24252
You can use lapply
:
ps <- lapply(themes1, gplot1)
ps[[1]]
ps[[2]]
Upvotes: 1