Search code examples
rggplot2scale-color-manual

Changing default plot colors in R for categorical values


I just scripted the plot below, for which I would like to modify the colors:

library(ggplot2)
library(arm)

df <- tibble::tribble(~Proportion, ~Lower,~Upper, ~Area,~Time,
                      invlogit(-0.2486022), invlogit(-0.654304025), invlogit(0.157099625), "SNP", "Day",
                      0.6878081, ( 0.6878081-0.0961473),(0.6878081+ 0.0961473), "SNP", "Night",
                      invlogit(-0.9417583), invlogit(-1.394725916), invlogit(-0.488790684),"LGCA", "Day",
                      invlogit(-0.1771685), invlogit(-0.630136116),invlogit(0.275799116), "LGCA","Night")
df


dfnew <- df %>% 
  mutate(ymin = Proportion - Lower,
         ymax = Proportion + Upper)

p <-   ggplot(data = dfnew, aes(x = Time, y = Proportion, color=Area)) +

  geom_point(size = 6, stroke = 0, shape = 16) + 
  geom_errorbar(aes(y=Proportion, ymin = Lower, ymax = Upper),width=0.1,size=1)


p<-p+theme(axis.text=element_text(size=15),
             axis.title=element_text(size=20))

p

Indeed, I would like SNP to be in color name "coral" and LGCA in color name "darkgoldenrod2".

Additionally, because the error bars overlap each other, I also would like to slightly move the points and error bars, so that there's no overlap.

I'm very new to R, so if at least somebody can point me towards the right direction, that will be very appreciated!

Thanks in advance.


Solution

  • I believe what you're after here is the following.

    Within the scale_color_manual call you have to manually assign a value to each factor level, as shown here:

    p <-   ggplot(data = dfnew, aes(x = Time, y = Proportion, color=Area)) +
      geom_point(size = 6, stroke = 0, shape = 16) + 
      geom_errorbar(aes(y=Proportion, ymin = Lower, ymax = Upper),width=0.1,size=1) + 
      theme(axis.text=element_text(size=15),
               axis.title=element_text(size=20)) +
      scale_color_manual(values = c("SNP" = "coral", 
                                    "LGCA" = "darkgoldenrod2"))
    p
    

    EDIT: I missed the second part of your question, the error bars and points can each be positioned to not overlap using position_dodge within each of geom_point and geom_errorbar as follows:

      geom_point(size = 6, stroke = 0, shape = 16, 
                 position = position_dodge(width = 0.1)) + 
      geom_errorbar(aes(y=Proportion, ymin = Lower, ymax = Upper),width=0.1,size=1,
                    position = position_dodge(width = 0.1)) + 
      theme(axis.text=element_text(size=15),
               axis.title=element_text(size=20)) +
      scale_color_manual(values = c("SNP" = "coral", 
                                    "LGCA" = "darkgoldenrod2"))
    p
    

    Final plot