首页 文章

使用ggplot2在dplyr链中进行子集/过滤

提问于
浏览
3

我想制作一个斜率图,沿着this的线条(没有双关语) . 理想情况下,我想在dplyr风格的链中完成所有操作,但是当我尝试将数据子集化以添加特定的 geom_text 标签时,我遇到了麻烦 . 这是一个玩具示例:

# make tbl:

df <- tibble(
  area = rep(c("Health", "Education"), 6),
  sub_area = rep(c("Staff", "Projects", "Activities"), 4),
  year = c(rep(2016, 6), rep(2017, 6)),
  value = rep(c(15000, 12000, 18000), 4)
) %>% arrange(area)


# plot: 

df %>% filter(area == "Health") %>% 
  ggplot() + 
  geom_line(aes(x = as.factor(year), y = value, 
            group = sub_area, color = sub_area), size = 2) + 
  geom_point(aes(x = as.factor(year), y = value, 
            group = sub_area, color = sub_area), size = 2) +
  theme_minimal(base_size = 18) + 
  geom_text(data = dplyr::filter(., year == 2016 & sub_area == "Activities"), 
  aes(x = as.factor(year), y = value, 
  color = sub_area, label = area), size = 6, hjust = 1)

但这给了我 Error in filter_(.data, .dots = lazyeval::lazy_dots(...)) : object '.' not found . 使用子集而不是 dplyr::filter 给我一个类似的错误 . 我在SO / Google上发现的是this问题,它解决了一个稍微不同的问题 .

在这样的链中对数据进行子集化的正确方法是什么?

Edit :我的代表是一个简单的例子,在实际工作中我有一条长链 . Mike的评论适用于第一种情况,但不适用于第二种情况 .

2 回答

  • 3

    如果将绘图代码包装在 {...} 中,则可以使用 . 指定先前计算结果的插入位置:

    library(tidyverse)
    
    df <- tibble(
      area = rep(c("Health", "Education"), 6),
      sub_area = rep(c("Staff", "Projects", "Activities"), 4),
      year = c(rep(2016, 6), rep(2017, 6)),
      value = rep(c(15000, 12000, 18000), 4)
    ) %>% arrange(area)
    
    df %>% filter(area == "Health") %>% {
        ggplot(.) +    # add . to specify to insert results here
            geom_line(aes(x = as.factor(year), y = value, 
                          group = sub_area, color = sub_area), size = 2) + 
            geom_point(aes(x = as.factor(year), y = value, 
                           group = sub_area, color = sub_area), size = 2) +
            theme_minimal(base_size = 18) + 
            geom_text(data = dplyr::filter(., year == 2016 & sub_area == "Activities"),    # and here
                      aes(x = as.factor(year), y = value, 
                          color = sub_area, label = area), size = 6, hjust = 1)
    }
    

    虽然那个情节可能不是你真正想要的,但至少它会运行,所以你可以编辑它 .

    发生了什么:通常 %>% 将左侧(LHS)的结果传递给右侧的第一个参数(RHS) . 但是,如果将RHS包装在大括号中, %>% 只会将结果传递给显式放置 . 的位置 . 此公式对于嵌套的子管道或其他复杂的调用(如ggplot链)非常有用,否则只能通过使用_1513549重定向来对其进行排序 . 有关详细信息和选项,请参阅 help('%>%', 'magrittr') .

  • 6

    写作:

    geom_text(data = df[df$year == 2016 & df$sub_area == "Activities",],...
    

    代替

    geom_text(data = dplyr::filter(., year == 2016 & sub_area == "Activities"),...
    

    使它工作但你仍然有关于文本位置的问题(你应该能够轻松找到关于该问题的SO的帮助) .

相关问题