Change the overlaying order of lines in ggplot

前端 未结 2 1980
走了就别回头了
走了就别回头了 2021-01-17 12:13

Suppose I have this plot:

library(ggplot2)
pl_data <- data.frame(x = rep(c(1, 2), times = 3), y = c(0, 1, 1, 0, .7, .7), col = rep(c(\"r\", \"b\", \"g\"),         


        
相关标签:
2条回答
  • 2021-01-17 12:47
    library(ggplot2)
    df <- data.frame(
      x = rep(c(1, 2), times = 3), 
      y = c(0, 1, 1, 0, .7, .7), 
      col = rep(c("r", "b", "g"), each = 2))
    
    ggplot() + 
      geom_line(data = df[3:4,], aes(x = x, y = y), color = 'blue', size = 3) +
      geom_line(data = df[5:6,], aes(x = x, y = y), color = 'green', size = 3) +
      geom_line(data = df[1:2,], aes(x = x, y = y), color = 'red', size = 3)
    
    0 讨论(0)
  • 2021-01-17 12:59

    So actually the last level of col is on the top. So you need to change the order of the factor and reverse the colors as red is automatically mapped to the first level (used standard colors to illustrate the problem):

    pl_data$col <- factor(pl_data$col, c("r", "g", "b"))
    ggplot(pl_data, aes(x = x, y = y, color = col)) +
        geom_line(size = 3) + 
        scale_color_manual(values = c(r = "blue", g = "green", b = "red"))
    
    ## with standard colors of ggplot2, function taken from:
    ## http://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette
    
    ggplotColours <- function(n = 6, h = c(0, 360) + 15) {
      if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
      hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
    }
    pal <- setNames(ggplotColours(3), c("b", "g", "r"))
    ggplot(pl_data, aes(x = x, y = y, color = col)) +
        geom_line(size = 3) + 
        scale_color_manual(values = pal, breaks = c("b", "g", "r"))
    

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