简体   繁体   English

如何通过将主题作为ggplot2中函数的参数传递来绘制不同的主题?

[英]How to plot different themes by passing themes as arguments of a function in ggplot2?

I referred some articles of passing function as an argument and I hope I could then produce plots with different themes by using ggplot2. 我以传递函数的一些文章作为参数,希望通过使用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: 我尝试了gplot1()却一无所获,而我尝试了gplot2()时却得到了警告消息并且没有任何图:

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! 非常感谢!

You can use lapply : 您可以使用lapply

ps <- lapply(themes1, gplot1)
ps[[1]]

在此处输入图片说明

ps[[2]]

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM