如何在ggplot中更改geom_line()中行的颜色顺序

时间:2018-05-06 14:46:31

标签: r ggplot2 colors

我想更改此图中的线条颜色,使它们处于“自然”或原始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 个答案:

答案 0 :(得分: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')) 

enter image description here

因为这些线条纵横交错,所以它们只能按照自然顺序存在一年。您需要选择最适合您想要讲述的故事的那个。