scale_fill_manual failed to show all colors

1,001 views
Skip to first unread message

King Wai Lau

unread,
Nov 7, 2017, 2:09:56 PM11/7/17
to ggplot2
Hi Everyone,

I am trying to show all 7 colors in colvalue on legend while only 5 in discrete value in the Data. I have added the drop=FALSE in the scale_fill_manual function but no luck. Does anyone know how?

library("ggplot2")

Data <- data.frame(gene=as.character(unlist(lapply(1:10,function(x) {rep(x,5)}))),sample=as.character(rep(seq(1,5,by=1),10)),value=as.character(sample.int(5,50,replace=TRUE)),stringsAsFactors=FALSE)

colfunc <- colorRampPalette(c("white", "steelblue"))
colvalue<-colfunc(5+2)
names(colvalue)<-seq(0,5+1,by=1)

ggplot(Data, aes(x=sample, y=gene)) + geom_tile(aes(fill=as.factor(value)),colour = "black") + scale_fill_manual(values = colvalue, drop=FALSE)


Thanks in advance

Brandon Hurr

unread,
Nov 7, 2017, 3:03:45 PM11/7/17
to King Wai Lau, ggplot2
King, 

The factor used to identify your values is made in the ggplot2 call and does not contain the levels that you are assigning for the colors so those extra levels are ignored. Best to define these from the beginning and use them.

Data %>%
mutate(value = lvls_expand(as.factor(value), as.character(0:6))) %>%
ggplot(., aes(x=sample, y=gene)) +
geom_tile(aes(fill=value), colour = "black") +
scale_fill_manual(values = colvalue, drop=FALSE)


forcats::lvls_expand makes adding those levels pretty easy, but needs to be a character vector. You still need drop = FALSE in the scale_*_manual() call.

HTH,
B

--
--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility
 
To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+unsubscribe@googlegroups.com
More options: http://groups.google.com/group/ggplot2

---
You received this message because you are subscribed to the Google Groups "ggplot2" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ggplot2+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages