代码之家  ›  专栏  ›  技术社区  ›  elliot

如何更改ggplot中geom\u line()中线条的颜色顺序

  •  2
  • elliot  · 技术社区  · 6 年前

    我想更改此绘图中的线条颜色,使其处于“自然”或原始状态 RColorBrewer 颜色顺序。此代码生成以下绘图:

    df <- data_frame(GeoName = rep(LETTERS, 3)) %>% 
        arrange(GeoName) %>% 
        mutate(year = rep(c(2009, 2010, 2011), 26),
               percent_change = sample(seq(-3, 3, .1), 78, T))
    
    #create my color ramp function
    YlGnBu <- colorRampPalette(RColorBrewer::brewer.pal(9, 'YlGnBu'))
    
    
    df %>% 
        ggplot(aes(year,
                   percent_change,
                   group = GeoName,
                   # order = GeoName,               <- does not accomplish my goal
                   color = GeoName))+
        geom_point(show.legend = F)+
        geom_line(show.legend = F)+
        scale_color_manual(values = YlGnBu(n_distinct(df$GeoName)))+ # color function 
        scale_x_continuous(breaks = c(2009, 2010, 2011))+              # from above
        theme(panel.background = element_blank(),
              panel.grid = element_blank(),
              axis.line = element_line(color = 'black')) 
    

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   Claus Wilke    6 年前

    你需要转身 GeoName 并将其级别设置为正确的顺序。例如,我们可以按2009年的值着色:

    library(ggplot2)
    library(dplyr)
    
    df <- data_frame(GeoName = rep(LETTERS, 3)) %>% 
      arrange(GeoName) %>% 
      mutate(year = rep(c(2009, 2010, 2011), 26),
             percent_change = sample(seq(-3, 3, .1), 78, T))
    
    # here is the change:
    df$GeoName <- factor(
                    df$GeoName,
                    levels = (filter(df, year == 2009) %>%
                      arrange(desc(percent_change)))$GeoName)
    
    #create my color ramp function
    YlGnBu <- colorRampPalette(RColorBrewer::brewer.pal(9, 'YlGnBu'))
    
    
    df %>% 
      ggplot(aes(year,
                 percent_change,
                 group = GeoName,
                 color = GeoName))+
      geom_point(show.legend = F)+
      geom_line(show.legend = F)+
      scale_color_manual(values = YlGnBu(n_distinct(df$GeoName)))+ # color function 
      scale_x_continuous(breaks = c(2009, 2010, 2011))+              # from above
      theme(panel.background = element_blank(),
            panel.grid = element_blank(),
            axis.line = element_line(color = 'black')) 
    

    enter image description here

    因为这些线纵横交错,它们只能在一年内按自然顺序排列。你需要选择一个最适合你想要讲述的故事的。