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 a bar color without show it in legend

I have a plot like below. I would like to:
Q1: replace darkgrey to lightgrey color without it show up in legend. Is it possible?

Q2: it is possible to have legend for the grey part. Maybe set it to "Length1-Length2"? It will be stand along legend, instead of adding it to ID legend.

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

df<- structure(list(ID = c("A", "B", "C", "D"), Length1 = c(15, 12, 
6, 9), Length2 = c(7, 8, 3, 9)), row.names = c(NA, -4L), class = c("tbl_df", 
"tbl", "data.frame"))
ggplot(data = df)  +
   geom_bar(aes(y =  ID, x = Length1), stat = "identity")+ 
   geom_bar(aes(y =  ID, x = Length2, fill = ID), stat = "identity")

>Solution :

  1. add fill="lightgray" to the first geom_bar (not within aes(..)); and
  2. we can "cheat" by using an otherwise-unused aesthetic to create another legend, I’ll use linetype.
ggplot(data = df)  +
   geom_bar(aes(y =  ID, x = Length1, linetype = "Len1 - Len2"),
            fill = "lightgray", stat = "identity") +
   geom_bar(aes(y =  ID, x = Length2, fill = ID), stat = "identity") + 
   scale_linetype_discrete(name = NULL)

enter image description here

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