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

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

Leave a Reply