jeudi 26 mai 2016

Using ifelse statement to define colour in ggplot2 bar graph

I'm trying to get the average bar within my dataset to have a different colour to the rest of the variables. After looking into it I thought ifelse would be the best function for this (as I need to repeat with many different datasets, so dont want to use the scale_fill_manual option).

So within my ggplot code I used this:

  • geom_bar(width=0.66,position="stack",stat = "identity",fill=ifelse(F12$Mean==F12_ave$Mean,"Blue","Black"))

From what I understand, the average should equal the statement here "TRUE" therefore it should be coloured blue, however it's not.

What am I doing wrong?

Ps: Is there also a way to reposition the average bar at the bottom of the graph?

    ggplot(F12,aes(reorder(Country,Mean),Mean))+
  geom_bar(width=0.66,position="stack",stat = "identity",fill=ifelse(F12$Mean==F12_ave$Mean,"Blue","Black"))+
  ylab("")+xlab("")+
  geom_text(aes(label=format(round(F12$Mean, 0), nsmall = 0)),family="Open Sans",colour="white", size=4.5, hjust=1.2)+
  coord_flip()+scale_y_continuous(expand = c(0,0))

F12<-structure(list(Country = structure(1:4, .Label = c("Italy", "Portugal", 
"Uk ", "Average"), class = "factor"), Mean = c(40.2777777777778, 
51.0416666666667, 47.5694444444444, 46.2962962962963)), .Names = c("Country", 
"Mean"), class = "data.frame", row.names = c(NA, -4L))

F12_ave<-subset(F12,Country=="Average")

Aucun commentaire:

Enregistrer un commentaire