Home > Software engineering >  Using ggplot2 why does changing the color palette result in all grey?
Using ggplot2 why does changing the color palette result in all grey?

Time:03-31

Built into my app I have the ability to change the color palette including for color vision deficiencies. However, one of my graphs works fine with the R4 but is all grey with the Okabe-Ito palette and lists the colors' names in the legend. What am I doing wrong?

data<-as.data.frame(rbind(15.29,84.71))
         data<-cbind(x=c("Total Measurement Variance","Total Measurement Variance"),y=data,Group=c("Repeatability","Reproducibility"))
         colnames(data)<-c("x","y","Source")

color=palette.colors(n = 8,palette = "R4")

p<-ggplot(data=data,aes(x=x,y=y,fill=Source,label=y)) 
     geom_bar(stat="identity") 
     geom_label(aes(group=Source),fill="white",label=paste0(data$y,"%"),position=position_stack(vjust=.5)) 
     scale_y_continuous(labels=function (x) paste0(x,"%")) 
     scale_fill_manual(values=color[-1]) 
     labs(title="Components of Variation",x="",y="% of Measurement Error Variance")
p

color=palette.colors(n = 8,palette = "Okabe-Ito")

p<-ggplot(data=data,aes(x=x,y=y,fill=Source,label=y)) 
     geom_bar(stat="identity") 
     geom_label(aes(group=Source),fill="white",label=paste0(data$y,"%"),position=position_stack(vjust=.5)) 
     scale_y_continuous(labels=function (x) paste0(x,"%")) 
     scale_fill_manual(values=color[-1]) 
     labs(title="Components of Variation",x="",y="% of Measurement Error Variance")
p

CodePudding user response:

The problem comes from the fact that for some reason, palette.colors returns a named vector when you use palette = "Okabe-Ito" Compare the output here

palette.colors(n = 8,palette = "R4")
# [1] "#000000" "#DF536B" "#61D04F" "#2297E6" "#28E2E5" "#CD0BBC"
# [7] "#F5C710" "#9E9E9E"

palette.colors(n = 8,palette = "Okabe-Ito")
#         black        orange       skyblue   bluishgreen 
#     "#000000"     "#E69F00"     "#56B4E9"     "#009E73" 
#        yellow          blue    vermillion reddishpurple 
#     "#F0E442"     "#0072B2"     "#D55E00"     "#CC79A7" 

When you use scale_fill_manual(values=), if you pass a named vector, then it will try to match up the names of in the color vector to the names of the levels of your factor. Since your Source values are "Repeatability" and "Reproducibility" and not values like "orange" and "skyblue", the matching doesn't work and you just get grey. If you remove the names, then it won't try to do the matching.

color <- unname(palette.colors(n = 8, palette = "Okabe-Ito"))

should work

  • Related