Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change bars colors with scale_fill_manual() in R?

I want my bars to correspond to a legend and to have them colored with my own color, not the default one.

# library
library(ggplot2)

# create a dataset
specie <- c(rep("IFNg_WNH", 2) , 
            rep("IFNg_AA", 2), 
            rep("IL1b_WNH", 2), 
            rep("IL1b_AA", 2),
            rep("IL6_WNH", 2), 
            rep("IL6_AA", 2) 
)


condition <- rep(c("down", "up"), 6)

value <- c(452,216,
           348,327,
           207,61,
           75,53,
           177,191,
           379,318)
data <- data.frame(specie,condition,value)

data

# Grouped
p <- ggplot(data, aes(fill=condition, y=value, x=specie)) +
  geom_bar(position="dodge", stat="identity")


z <- p+labs(y = "Number of genes", x = "Cytokines")+
  theme_classic()+
  theme(plot.title = element_text(hjust = 0.5))+
  theme(axis.line=element_line(size=1))+
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))+
  scale_fill_discrete(labels=c('up', 'down'))

z

Once I add

z + scale_fill_manual(values=c('#eb4034','#0a0a0a'))

The color is changing but the legend reverts to the wrong one. What is happening?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Adding type to scale_fill_discrete

type: One of the following:

• A character vector of color codes.

• A list of character vectors of color codes.

• A function that returns a discrete colour/fill scale

ggplot(data, aes(fill=condition, y=value, x=specie)) + 
  geom_bar(position="dodge", stat="identity") + 
  labs(y = "Number of genes", x = "Cytokines") + 
  theme_classic() + 
  theme(plot.title = element_text(hjust = 0.5)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA)) + 
  scale_fill_discrete(labels=c('up', 'down'), type=c('#eb4034','#0a0a0a'))

bar plot

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading