In R ggplot2: How to assign colors in scale_fill_manual to a factor?

Viewed 1578

I have a sample dataset which I want to plot in ggplot, assigning with scale_fill_manual an individual color for each factor in the variable group. However, the individual assignment does not work properly, as you can see the factors a and b do not get a different color. Here is my code and the resulting plot.

#data
trt<-c("trt1","trt2","trt3","trt4","trt5","trt6","trt7")
emmean<-c(7.75,7.5,5.75,7,6,8,4)
group<-c("c","c","b","bc","b","c","a")

#specify color vector to get as many colors as group levels
library(RColorBrewer)
color_pallete_function <- colorRampPalette(
  colors = brewer.pal(8,"Dark2"),
  space = "Lab")

dat<-data.frame(trt,emmean,group)

dat$group<-as.factor(dat$group)
num_colors <- nlevels(dat$group)
diamond_color_colors <- color_pallete_function(num_colors)

#letter display plot
ggplot(data=dat, aes(x=reorder(trt,emmean),y=emmean,fill=group)) +
  geom_bar( stat="identity", width=0.8) +
  scale_fill_manual(values =diamond_color_colors[dat$group])+
  #geom_errorbar(aes(ymin=lower.CL, ymax=upper.CL), width=0.4) +
  geom_text(aes(y=8, label=group, angle=90)) +
  theme(legend.position = "none",
        axis.text.x = element_text(angle = 45,hjust=1)) + 
  annotate(geom="label", y=1, x=length(rownames(dat))-1, size=3, color="black", fill="white",
           label="Means with the same letter are according\n  to Tukey test (alpha=5%) not significantly different.")
 

enter image description here

How can this be solved?

1 Answers

To assign colors to categories in a robust way name your color vector and use this named color vector inside scale_fill_manual. Try this:

library(ggplot2)
library(RColorBrewer)

trt<-c("trt1","trt2","trt3","trt4","trt5","trt6","trt7")
emmean<-c(7.75,7.5,5.75,7,6,8,4)
group<-c("c","c","b","bc","b","c","a")

#specify color vector to get as many colors as group levels
color_pallete_function <- colorRampPalette(
  colors = brewer.pal(8,"Dark2"),
  space = "Lab")

dat<-data.frame(trt,emmean,group)

dat$group<-as.factor(dat$group)
num_colors <- nlevels(dat$group)
diamond_color_colors <- color_pallete_function(num_colors)
# Name your color vector
diamond_color_colors <-setNames(diamond_color_colors, levels(dat$group))

#letter display plot
ggplot(data=dat, aes(x=reorder(trt,emmean),y=emmean,fill=group)) +
  geom_bar( stat="identity", width=0.8) +
  scale_fill_manual(values = diamond_color_colors)+
  geom_text(aes(y=8, label=group, angle=90)) +
  theme(legend.position = "none",
        axis.text.x = element_text(angle = 45,hjust=1)) + 
  annotate(geom="label", y=1, x=length(rownames(dat))-1, size=3, color="black", fill="white",
           label="Means with the same letter are according\n  to Tukey test (alpha=5%) not significantly different.")

Related