if else condition in ggplot to add an extra layer

前端 未结 4 586

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 09:14

    library(ggplot2)
    
    # 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))
    }))
    
    tmp.data<-c(1,2,3) # in this case the condition is fulfilled
    
    p <- ggplot(mry, aes(x=year, y=number, group=rating))
    
    # this won't "loop through" the data points but it's what you asked for
    if (tmp.data[1]!="no value") {
      p <- p + geom_point() + geom_line()
    } else {
      p <- p + geom_line()
    }
    p
    

    g1

    but perhaps this is more like what you really want?

    mry$rating <- factor(mry$rating)
    p <- ggplot(mry, aes(x=year, y=number, group=rating))
    p <- p + geom_line()
    p <- p + geom_point(data=mry[!(mry$rating %in% tmp.data),], 
                        aes(x=year, y=number, group=rating, color=rating), size=2)
    p <- p + scale_color_brewer()
    p
    

    g2

提交回复
热议问题