【问题标题】:How can I change the color order of lines in geom_line() in ggplot如何更改 ggplot 中 geom_line() 中线条的颜色顺序
【发布时间】:2018-05-06 14:46:31
【问题描述】:

我想更改此图中的线条颜色,使其处于“自然”或原始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')) 

【问题讨论】:

    标签: r ggplot2 colors


    【解决方案1】:

    您需要将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')) 
    

    因为线条纵横交错,它们只能自然排列一年。您需要选择最适合您要讲述的故事的那个。

    【讨论】:

      猜你喜欢
      • 2018-06-11
      • 1970-01-01
      • 2022-08-15
      • 2018-01-06
      • 1970-01-01
      • 2011-07-07
      • 2018-08-25
      • 2021-11-27
      相关资源
      最近更新 更多