【问题标题】:How to get bars to retain their colors after reorder?重新排序后如何让酒吧保持颜色?
【发布时间】:2017-11-27 02:20:59
【问题描述】:

在这里,我希望条形图使颜色与类别保持一致。数据可能会不时发生变化——因此条形图的顺序可能会发生变化——但我想保留(此处)团队名称的颜色。

teams <- c("Riverside Reds", "Oakland Oranges", "Yucaipa Yellows", "Glendale Greens", "Bakersfield Blues", "Irvine Indigos", "Vacaville Violets")
rainbow_colors <- c("red", "orange", "yellow", "green", "blue", "#4B0082", "violet")
wins <- sample(64:104, length(teams))
df <- data.frame(teams, rainbow_colors, wins)

df %>%
  arrange(desc(wins)) %>%
ggplot(aes(x = reorder(teams, wins),
       y = wins)) + 
  coord_flip() +
  geom_bar(aes(fill = teams),
       stat = "identity") +
  labs(title = "Team Standings",
   x = "") +
  scale_fill_manual(breaks = teams, 
    values = rainbow_colors)

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这是你想要的吗?

    您需要做的就是在scale_fill_manual 中指定名称:

     scale_fill_manual(breaks = teams, 
                    values = setNames(rainbow_colors, teams))
    

    完整的可重现代码:

    library(dplyr)
    library(ggplot2)
    
    set.seed(1)
    teams <- c("Riverside Reds", "Oakland Oranges", "Yucaipa Yellows", "Glendale Greens", "Bakersfield Blues", "Irvine Indigos", "Vacaville Violets")
    rainbow_colors <- c("red", "orange", "yellow", "green", "blue", "#4B0082", "violet")
    wins <- sample(64:104, length(teams))
    df <- data.frame(teams, rainbow_colors, wins)
    
    
    
    df %>%
      arrange(desc(wins)) %>%
      ggplot(aes(x = reorder(teams, wins),
                 y = wins)) + 
      coord_flip() +
      geom_bar(aes(fill = teams),
               stat = "identity") +
      labs(title = "Team Standings",
           x = "") +
      scale_fill_manual(breaks = teams, 
                        values = setNames(rainbow_colors, teams))
    

    【讨论】:

      猜你喜欢
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 2015-09-10
      • 2014-01-10
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      相关资源
      最近更新 更多