Highlight minimum and maximum points in faceted ggplot2 graph in R

前端 未结 1 1156
攒了一身酷
攒了一身酷 2020-12-18 14:25

I am using the built-in economics (from the ggplot2 package) dataset in R, and have plotted a time-series for each variable in the same graph using

1条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 15:16

    Method 1: Using Joins

    This can be nice when you want to save the filtered subsets


    library(reshape2)
    library(ggplot2)
    library(dplyr)
    
    me <- melt(economics, id=c("date"))
    
    me %>%
      group_by(variable) %>%
      summarise(min = min(value),
                max = max(value)) -> me.2
    
    left_join(me, me.2) %>%
      mutate(color = value == min | value == max) %>%
      filter(color == TRUE) -> me.3
    
    ggplot(data=me, aes(x = date, y = value)) + 
      geom_line() +
      geom_point(data=me.3, aes(x = date, y = value), color = "red") +
      facet_wrap(~variable, ncol=1, scales='free_y')
    

    Method 2: Simplified without Joins

    Thanks @Gregor

    me.2 <- me %>%
      group_by(variable) %>%
      mutate(color = (min(value) == value | max(value) == value))
    
    ggplot(data=me.2, aes(x = date, y = value)) +
      geom_line() +
      geom_point(aes(color = color)) +
      facet_wrap(~variable, ncol=1, scales="free_y") +
      scale_color_manual(values = c(NA, "red"))
    

    Plot

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