【发布时间】:2018-04-10 12:08:18
【问题描述】:
在做数据分析的时候,我们经常使用dplyr在具体geoms中进一步修改dataframe。这允许我们稍后更改 ggplot 的默认数据框,并且一切正常。
template <- ggplot(db, aes(x=time, y=value)) +
geom_line(data=function(db){db %>% filter(event=="Bla")}) +
geom_ribbon(aes(ymin=low, ymax=up))
ggsave( template, "global.png" )
for(i in unique(db$simulation))
ggsave( template %+% subset(db, simulation==i), paste0(i, ".png")
是否有更好/更短的方法来指定filter 命令,例如使用一些神奇的.?
编辑
澄清一些 cmets:通过使用geom_line(data = db %>% filter(event=="Bla")),当我稍后使用%+% 更改默认数据帧时,该层不会更新。我真的打算将 geom_* 的 data 参数用作函数。
【问题讨论】:
-
geom_line(data = filter(db, event=="Bla"))或geom_line(data = db %>% filter(event=="Bla")) -
也可以在
ggplot之前声明db:db %>% ggplot(., aes(x=time, y = value)) + geom_line(filter(., event == "Bla")) [...]。 -
并将
for替换为by:by(db, db$simulation, function(subdf) { i <- subdf$simulation[[1]]; ggsave(template %+% subdf, paste0(i, ".png")) })