在这里,我希望条形图保持颜色与类别。数据可能会不时变化---因此条形图的顺序可能会发生变化---但我希望将颜色保留在(此处)团队名称中。
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)
答案 0 :(得分:2)
这是你想要的吗?
您需要做的就是在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))