【问题标题】:How to add geoms to a list-column of ggplot`s如何将几何添加到ggplot`s的列表列
【发布时间】:2020-07-26 11:33:53
【问题描述】:

基于this 问题,在取消嵌套data.frame 之后,我将逐行添加geoms 到接收到的绘图中,以便为每一行获取一个绘图,并在其组中突出显示行数据。

library(tidyverse) # using  version 1.3.0
mydata <- data_frame(group = c('a', 'a', 'a', 'b', 'b', 'b'),
                     x = c(1,2,3,5,6,7),
                     y = c(3,5,6,4,3,2))
mydata2 <- mydata %>% 
  group_by(group) %>% 
  nest() %>% 
  mutate(myplot = map(data, ~ggplot(data = .x, aes(x = x, y = y)) + geom_point()))
mydata2
# A tibble: 2 x 3
# Groups:   group [2]
  group data             myplot
  <chr> <list>           <list>
1 a     <tibble [3 x 2]> <gg>  
2 b     <tibble [3 x 2]> <gg>  

第一行的期望输出是这样的:

mydata2$myplot[[1]] + geom_point(mapping = aes(x=1,y=3),color = "red")


但是,当尝试在未嵌套的 data.frame 上实现此功能时,我失败了。 以下是我的三个尝试及其输出:

mydata3 <- mydata2 %>% 
  unnest(data) %>% 
  mutate(myplot2 = myplot + geom_point(mapping = aes(x=x,y=y),color = "red"))
mydata3$myplot2[[1]]
NULL
Warning message:
Unknown or uninitialised column: `myplot2`. 


mydata4 <- mydata2 %>% 
  unnest(data) %>% 
  mutate(myplot2 = list(myplot[[1]] + geom_point(mapping = aes(x=x,y=y),color = "red")))
mydata4$myplot2[[1]]

所有点都变红了! 这次尝试我得到了相同的输出:

mydata5 <- mydata2 %>% 
  unnest(data) %>% 
  mutate(myplot2 = map(myplot,~.x + geom_point(mapping = aes(x=x,y=y),color = "red")))
mydata5$myplot2[[1]]

所以我的问题是,有没有办法使用 tidyverse 获得第一个情节?

【问题讨论】:

    标签: r ggplot2 dplyr tidyverse purrr


    【解决方案1】:

    试试这个。诀窍是使用pmapxymyplot 上循环“逐行”。 xy 坐标通过 data 参数传递给 geom_point,这只是一个只有一行的 df:

    library(tidyverse)
    mydata <- data_frame(group = c('a', 'a', 'a', 'b', 'b', 'b'),
                         x = c(1,2,3,5,6,7),
                         y = c(3,5,6,4,3,2))
    
    mydata2 <- mydata %>% 
      group_by(group) %>% 
      nest() %>% 
      mutate(myplot = map(data, ~ggplot(data = .x, aes(x = x, y = y)) + geom_point()))
    
    mydata3 <- mydata2 %>%
      unnest(data) %>% 
      mutate(myplot2 = pmap(list(x, y, myplot), ~ ..3 + geom_point(data = data.frame(x = ..1, y = ..2), mapping = aes(x, y), color = "red")))
    
    mydata3$myplot2[[1]]
    

    reprex package (v0.3.0) 于 2020-04-13 创建

    【讨论】:

      猜你喜欢
      • 2022-10-04
      • 2011-01-17
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多