【问题标题】:How do I fill a bar plot with a specific colour palette according to the variables?如何根据变量用特定的调色板填充条形图?
【发布时间】:2021-04-22 01:43:40
【问题描述】:

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

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 更新

如果托盘中的变量与数据帧的顺序相同,它会起作用,但如果你稍微混合一下,它就不起作用了。将其更改为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

【问题讨论】:

  • fill = cor.partidos 更改为aes(fill = cor.partidos) 是否可以解决问题?如果没有,我们可以请minimal reproducible example ... ???
  • 我会尝试使用aes(..., fill = partido)。要使用您的自定义调色板,请尝试使用 + scale_fill_manual(values = cor.partidos)

标签: r ggplot2 colors geom-bar pallet


【解决方案1】:

正如我在评论中建议的那样,您可以通过在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多