Home > front end >  Colors for factor levels do not match when reordered using geom_errorbar in ggplot
Colors for factor levels do not match when reordered using geom_errorbar in ggplot

Time:10-01

There are several questions here that are similar, but not specifically dealing with this issue in geom_errorbar. I have tried many of the solutions for other geoms, but they have not worked for me.

I am trying to create a bar chart with error bars. Pretty straightforward, except that I need to reorder the levels of the x axis when making the figure. When I apply the code below, the values for the bars and the error bars end up in the correct place. The color for the bars also ends up in the correct place. I cannot figure out how to assign the color of the error bars to the correct place, however. If anyone can be of assistance please let me know! Thank you. I want the colors of the errorbars to match that of "vals".

     xx<-c("one", "two", "three", "four", "five")
     yy<-c(4, 6, 8, 10, 12)
     zz<-c(0.5, 1, 2, 4, 5)
     add<-data.frame(xx, yy, zz)
     add$xx<-factor(add$xx, levels =c("five", "three", "two", "one", "four"))
     vals<-c("five"= "white", "three"="blue", "two"= "green", "one"= "orange", "four"= "black")
      vals2<-c("five"= "white", "three"="white", "two"= "white", "one"= "black", "four"= "black")
     graph1<-ggplot(data= add, aes(x=xx, y= yy, fill = xx)) 
      geom_bar(stat = "identity") 
      geom_errorbar(aes(ymin=yy-zz, ymax=yy zz, color=vals)) 
      scale_color_manual(values=vals, limits = c("five","three","two", "one", 
       "four"), guide="none") 
      scale_fill_manual(values=vals2, guide = "none")
      graph1

graph1 does not work and produces this:

graph 1

    graph2<-ggplot(data= add, aes(x=xx, y= yy, fill = xx)) 
    geom_bar(stat = "identity") 
    geom_errorbar(aes(ymin=yy-zz, ymax=yy zz), color=c("white", "blue", "green", "orange", 
    "black")) 
    scale_fill_manual(values=vals2, guide = "none")
    graph2

graph 2 also does not work and produces this:

graph2

I would like to find a way to make the error bar colors match "vals"

CodePudding user response:

You need to map the colors to xx, not to vals

ggplot(data = add, aes(xx, yy, fill = xx))  
  geom_col()  
  geom_errorbar(aes(ymin = yy - zz, ymax = yy   zz, color = xx))  
  scale_color_manual(values = vals)  
  scale_fill_manual(values = vals2, guide = "none")

enter image description here

  • Related