if else condition in ggplot to add an extra layer

前端 未结 4 587

say I want to plot two layers in ggplot, one containing points and another one containing lines if a certain criteria is fulfilled.

The code without the criteria cou

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 08:53

    Following the ggplot2 book, you can create a function which returns a list. Any NULL components will be ignored.

    library(ggplot2)
    library(ggplot2movies)
    
    # Summarise number of movie ratings by year of movie
    mry <- do.call(rbind, by(movies, round(movies$rating), function(df) {
        nums <- tapply(df$length, df$year, length)
        data.frame(rating=round(df$rating[1]), year = as.numeric(names(nums)), number=as.vector(nums))
    }))
    
    # create function to add points conditionally
    # If the list contains any NULL elements, they’re ignored. 
    my_plot <- function(point = FALSE){
        list(
            geom_line(),
            if (point) 
                geom_point()
        )
    
    }
    
    p <- ggplot(mry, aes(x=year, y=number, group=rating))
    p + my_plot()
    

    p + my_plot(point = TRUE)
    

    Created on 2020-02-25 by the reprex package (v0.3.0)

提交回复
热议问题