scale_fill_brewer() - specify na.colour and include NA in legend

1,242 views
Skip to first unread message

Olivia

unread,
Aug 30, 2014, 3:13:34 AM8/30/14
to ggp...@googlegroups.com
Hi there,

I would like to use scale_fill_brewer and the option to colour NAs by a specific colour, but include NAs in the legend. Reproducible example below.  Couple of options I've tried are commented out. I know if you aren't using scale_fill_brewer there's a work around by changing NA to something else in the data (http://stackoverflow.com/questions/18970580/how-to-plot-na-bar-with-ggplot2), but that would defeat me trying to use a sequential scale from brewer along with a very different colour for NA.  The legend item doesn't need to be called "NA".

I've gone from integer to a factor in the example because that's what I do with my real data (I'm leaving justifications for doing what is pretty much a stacked histogram out as the principle applies more widely anyhow). 

Any thoughts?
Best wishes,
Olivia

#install.packages("vegan")
#install.packages("ggplot2")
require(vegan)
require(ggplot2)

data(mite.env) # dataset from mite
miteenv_na <- mite.env # not to pollute mite if already using it
miteenv_na$familiarity <- sample(1:5)
miteenv_na[ , 6][sample(seq(miteenv_na[ , 6]), 10)] <- NA #introducing NAs
is.na(miteenv_na[ , 6]) # checking
miteenv_na$familiarity_fac <- factor(miteenv_na$familiarity, exclude = NULL)
levels(miteenv_na$familiarity_fac)
fam_labs <- levels(miteenv_na$familiarity_fac)

ggplot(miteenv_na, aes(x = Topo))+
  geom_bar(position = position_fill(), 
           stat = "bin", 
           aes(fill = familiarity_fac)) +
  scale_fill_brewer("Familiarity", 
                    type = "seq", 
                    na.value = "orange",
                    #labels = levels(miteenv_na$familiarity_fac))+ #doesn't work 
                    #labels = fam_labs) + #also doesn't work
  labs(y = "proportion") +
  theme_bw()

Olivia

unread,
Aug 30, 2014, 3:32:49 AM8/30/14
to ggp...@googlegroups.com
edit (commented out the changes but didn't fix the end of the scale_brewer():

#install.packages("vegan")
#install.packages("ggplot2")
require(vegan)
require(ggplot2)

data(mite.env) # dataset from mite
miteenv_na <- mite.env # not to pollute mite if already using it
miteenv_na$familiarity <- sample(1:5)
miteenv_na[ , 6][sample(seq(miteenv_na[ , 6]), 10)] <- NA #introducing NAs
is.na(miteenv_na[ , 6]) # checking
miteenv_na$familiarity_fac <- factor(miteenv_na$familiarity, exclude = NULL)
levels(miteenv_na$familiarity_fac)
fam_labs <- levels(miteenv_na$familiarity_fac)

ggplot(miteenv_na, aes(x = Topo))+
  geom_bar(position = position_fill(), 
           stat = "bin", 
           aes(fill = familiarity_fac)) +
  scale_fill_brewer("Familiarity", 
                    type = "seq", 
                    na.value = "orange") + #,
Reply all
Reply to author
Forward
0 new messages