1

I am looking for a way to control the colors of the sections in a bar plot so that they are stable if I then plot a subset of the data. I have seen this solution: How to assign colors to categorical variables in ggplot2 that have stable mapping?

Which looks very promising but I cannot seem to apply it to my data. I suspect this has to do with the layer I am using.

My code for generating the plot is:

   plot = ggplot(subdata,mapping = aes(x = as.factor(group))) +
        layer(geom = "bar", mapping = aes(fill = as.factor(NUM_MOTIFS)))

I can get the levels for the full dataset but when I tried adding it to the plot I kept getting this error:

  Error: Aesthetics must either be length one, or the same length as the dataProblems:as.factor(NUM_MOTIFS)

No matter where I put it... Any ideas?

EDIT: Example data:

fulldata = data.frame(group = rep("A",10), NUM_MOTIFS = c(0,0,1,1,1,2,2,2,4,5))
subdata = data.frame(group = rep("B",8), NUM_MOTIFS = c(0,0,1,1,2,2,2,2))

Many thanks!

Community
  • 1
  • 1
N.M
  • 685
  • 1
  • 9
  • 22

2 Answers2

1

I think this will do the trick. Note that you can choose other values for 'cbbPalette' (some examples).

fulldata = data.frame(group = rep("A",10), NUM_MOTIFS = c(0,0,1,1,1,2,2,2,4,5))
subdata = data.frame(group = rep("B",8), NUM_MOTIFS = c(0,0,1,1,2,2,2,2))
fulldata$NUM_MOTIFS=as.factor(as.character(fulldata$NUM_MOTIFS))
subdata$NUM_MOTIFS=as.factor(as.character(subdata$NUM_MOTIFS))

levels(subdata$NUM_MOTIFS)=levels(fulldata$NUM_MOTIFS)

cbbPalette <- c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")

ggplot(subdata,mapping = aes(x = as.factor(group),fill=NUM_MOTIFS)) +geom_bar()+
  scale_fill_manual(values=cbbPalette)


ggplot(fulldata,mapping = aes(x = as.factor(group),fill=NUM_MOTIFS)) +geom_bar()+
  scale_fill_manual(values=cbbPalette)
  • Thanks, Uri Obolski - this is exactly what I was looking for! I always knew I could trust in the internet :) – N.M Mar 17 '15 at 15:24
0

I think this is what you need:

#dummy data
fulldata = data.frame(group = rep("A",10), NUM_MOTIFS = c(0,0,1,1,1,2,2,2,4,5))
subdata = data.frame(group = rep("B",8), NUM_MOTIFS = c(0,0,1,1,2,2,2,2))

#merge full and subset data for plotting
df <- rbind(fulldata,subdata)
df$NUM_MOTIFS <- as.factor(df$NUM_MOTIFS)

#plot
ggplot(df,aes(group,fill=NUM_MOTIFS)) + geom_bar()

enter image description here

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • Thanks zx8754 but I would like to have it in separate plots (mainly to get an effect of same height between columns)... – N.M Mar 17 '15 at 13:26