如何根据变量用特定的调色板填充条形图?

How do I fill a bar plot with a specific colour palette according to the variables?

尝试通过创建我自己的调色板来分配每种可变颜色,但有些颜色混淆了。我应该如何解决这个问题?

cor.partidos <- c(
  `ps` = "#f71b75",
  `psd` = "#ef6438",
  `pcp-pev` = "#ff001d",
  `pan` = "#71af64",
  `outros` = "#f71b75",
  `nulos` = "#565557",
  `brancos` = "#aaa8ad",
  `l` = "#f71b75",
  `il` = "#f71b75",
  `ch` = "#393195",
  `cds-pp` = "#1192d8",
  `be` = "#b40020",
  `a` = "#f71b75") 

#test graph
bars <- ggplot(leg19, aes(x = partido, y = votos)) +
  geom_bar(stat="identity", 
           position="identity", 
           fill = cor.partidos) +
  geom_hline(yintercept = 0, size = 1, colour="#333333") +
  bbc_style() +
  theme(axis.text=element_text(size=10))+
  labs(subtitle = "Resultados Legislativas 2019",
       ylab = "votos")

更新为 mwe

如果 pallet 中的变量与数据帧的顺序相同,它会工作,但如果你稍微混合一下,它就不会工作。将其更改为 aes(fill = cor.partidos) 将不起作用:(

test.pallet <- c(
  `pink` = "#f71b75",
  `orange` = "#ef6438",
  `green` = "#71af64",
  `red` = "#ff001d",
  `other pink` = "#f71b72")

test.datafrane <- data_frame(
  name = c("pink","orange","red","green","other pink"),
  value = c(1,2,3,4,5)
)
test.datafrane$value <- as.numeric(test.datafrane$value)

test.graph <- ggplot(test.datafrane, aes(x = name, y = value)) +
  geom_bar(stat="identity", 
           position="identity", 
           fill = test.pallet)
test.graph

正如我在评论中所建议的那样,您可以通过将分类变量映射到 aes() 内的 fill 并使用 scale_fill_manual:

来实现您的结果
test.pallet <- c(
  `pink` = "#f71b75",
  `orange` = "#ef6438",
  `green` = "#71af64",
  `red` = "#ff001d",
  `other pink` = "#f71b72")

test.datafrane <- data.frame(
  name = c("pink","orange","red","green","other pink"),
  value = c(1,2,3,4,5)
)
test.datafrane$value <- as.numeric(test.datafrane$value)

library(ggplot2)

test.graph <- ggplot(test.datafrane, aes(x = name, y = value, fill = name)) +
  geom_bar(stat="identity", 
           position="identity") +
  scale_fill_manual(values = test.pallet)
test.graph