Display a summary line per facet rather than overall

前端 未结 1 498
礼貌的吻别
礼貌的吻别 2020-12-21 07:09

I am trying to do something similar to this question, but hoping to do it in a single block rather than caching values separately.

I am creating a chart similar to t

相关标签:
1条回答
  • 2020-12-21 07:51

    Because you said you wanted to do it in one block, note that among the many uses of . you can use it in geoms to refer to the original data argument to ggplot(). So here you can do an additional summarise to get the values for geom_vline. I also just reversed the aesthetics in geom_point instead of using coord_flip.

    library(tidyverse)
    
    mtcars %>%
      rownames_to_column("carmodel") %>%
      mutate(brand = substr(carmodel, 1, 4)) %>%
      group_by(brand, cyl) %>%
      summarize(avgmpg = mean(mpg)) %>%
      ggplot(aes(y=brand, x = avgmpg)) +
      geom_point() +
      geom_vline(
        data = . %>%
          group_by(cyl) %>%
          summarise(line = mean(avgmpg)),
        mapping = aes(xintercept = line)
        ) +
      facet_grid(cyl~., scales = "free_y")
    

    Created on 2018-06-21 by the reprex package (v0.2.0).

    0 讨论(0)
提交回复
热议问题