【问题标题】:Ggplot subset data functions and dplyrggplot 子集数据函数和 dplyr
【发布时间】: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 %&gt;% filter(event=="Bla")),当我稍后使用%+% 更改默认数据帧时,该层不会更新。我真的打算将 geom_* 的 data 参数用作函数。

【问题讨论】:

  • geom_line(data = filter(db, event=="Bla"))geom_line(data = db %&gt;% filter(event=="Bla"))
  • 也可以在ggplot之前声明db:db %&gt;% ggplot(., aes(x=time, y = value)) + geom_line(filter(., event == "Bla")) [...]
  • 并将for替换为byby(db, db$simulation, function(subdf) { i &lt;- subdf$simulation[[1]]; ggsave(template %+% subdf, paste0(i, ".png")) })

标签: r ggplot2 dplyr


【解决方案1】:

更好地阅读%&gt;%的文档后,我找到了解决方案:

将点占位符用作 lhs 当点用作 lhs 时,结果将是一个函数序列,即一个将整个右侧链依次应用于其输入的函数。请参阅示例。

因此,最好的方式来制定上面的例子,同时结合上面的建议:

db <- diamonds
template <- ggplot(db, aes(x=carat, y=price, color=cut)) + 
  geom_point() +
  geom_smooth(data=. %>% filter(color=="J")) +
  labs(caption="Smooths only for J color")
ggsave( template, "global.png" )
db %>% group_by(cut) %>% do(
  ggsave( paste0(.$cut[1], ".png"), plot=template %+% .)
)

【讨论】:

    猜你喜欢
    • 2017-12-09
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 2016-06-26
    相关资源
    最近更新 更多