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 default color for the value not defined when we use scale_fill_manual

I have a plot like below. As I am only focusing on name %in% c("A", "B", "C") , I will not define the color for other names. By default, they were filled with dark grey. By not defining the color for those, I was able to plot D, E out without showing them in the legend.

Is it a way I can change this default color to light grey? If so , how?

enter image description here

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

# Load ggplot2
library(ggplot2)

# Create data
data <- data.frame(
  name=c("A","B","C","D","E") ,  
  value=c(3,12,5,18,45)
  )

# Barplot
ggplot(data, aes(x=name, y=value, fill=name)) + 
  geom_bar(stat = "identity")   +
  scale_fill_manual(
    values = c("A"="red", "B"="green", "C"="blue") )

>Solution :

You could use the argument na.value to change the default color to light grey like this:

# Load ggplot2
library(ggplot2)

# Create data
data <- data.frame(
  name=c("A","B","C","D","E") ,  
  value=c(3,12,5,18,45)
)

# Barplot
ggplot(data, aes(x=name, y=value, fill=name)) + 
  geom_bar(stat = "identity")   +
  scale_fill_manual(
    values = c("A"="red", "B"="green", "C"="blue"), 
    na.value = "lightgrey")

Created on 2023-05-10 with reprex v2.0.2

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