rggplot2colorsgeom-barpallet

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


Trying to assing each variable colour by creating my own colour palette, but some of the colours get mixed up. Any ideas on how I should fix this?

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")

bars

update with a mwe

It will work if the variables in the pallet are in the same order as the dataframe but if you mix it around a bit it won't work. Changing it to aes(fill = cor.partidos) won't work :(

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

test.graph

test.graph with aes(fill = test.pallet)


Solution

  • As I suggested in my comment you could achieve your result by mapping your categorical var on fill inside aes() and make use of 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