3

I need to create one-row heatmap, that occasionally will be derived from NA-only column, but has to be displayed anyway. In the example below generating heatmap from p2 column will render "Error: Must request at least one colour from a hue palette.". Is there any way to force ggplot to display an "empty" heatmap?

library(ggplot2)
id <- letters[1:5]
p1 <- factor(c(1,NA,2,NA,3))
p2 <- factor(c(NA,NA,NA,NA,NA))
dat <- data.frame(id=id, p1=p1, p2=p2)

ggplot(dat, aes(x=id,y="identity")) + geom_tile(aes(fill = p1), colour = "white") #works fine

ggplot(dat, aes(x=id,y="identity")) + geom_tile(aes(fill = p2), colour = "white") #renders error
djneuron
  • 81
  • 4
  • 1
    What if you add `scale_fill_manual(values = "white")` to the one that doesn't work? Not sure exactly what you want it to look like in that case. – MrFlick Jan 02 '20 at 19:52
  • @MrFlick This did solve the problem: ggplot(dat, aes(x=id,y="identity")) + geom_tile(aes(fill = p2)) + scale_fill_manual(values = "red") Thanks for help! – djneuron Jan 02 '20 at 20:29
  • If the question is answered to your satisfaction, please consider accepting the answer by ticking the checkmark next to it - this way it won't flag as 'unanswered' any more. Thanks – tjebo Jan 03 '20 at 10:24

1 Answers1

5

I think if you explicitly tell ggplot how to handle NA values using the na.value inside a scale_fill_manual call. This should take care of your issue, or at least head you in the right direction:

ggplot(dat, aes(x=id,y="identity")) + 
  geom_tile(aes(fill = p2), colour = "white") + 
  scale_fill_manual(values = "white", 
                    na.value = "black") 

You can change the values argument to better handle the colors you like

Dave Gruenewald
  • 5,329
  • 1
  • 23
  • 35