Search code examples
rggplot2geom-bar

Order geom_bar by groups


I am new in R. I can order the legend but I cannot order the graphic as I want (Produc., Proc., Org., Mark.). I would like to sort the chart like this legend (image chart). I am using this code. It can be only reorder but I don't find a good solution. Thanks

ggplot(grado,aes(Label,Grado,fill=as.factor(InnoCat)))+
  geom_bar(position = "dodge",stat="identity")+
  facet_wrap(~InnoCat,nrow=4, scales = "free_y")+
  coord_trans() +
  scale_fill_manual("Leyenda",
                    values = c(
                      "Mark." = "#d982d4",
                      "Org." = "#667ee8",
                      "Proc." = "#53c24f",
                      "Produc." = "#e6914c"
                    )) +
  guides(fill = guide_legend(reverse = TRUE))

Data example (grado is the name of my dataset)

structure(list(Nodo = c("P1", "P2", "P3", "P4", "P5", "P6", "P7", 
"P8", "P9", "P10", "P11", "Cooperativas", "Cursos o ferias", 
"Empresas", "Familia y Amigos", "Grupos de Consumo", "Instituciones", 
"Investigación", "Organizaciones", "Técnicos"), Grado = c(0.2, 
0.2, 0.4, 0.4, 0.2, 0.2, 0.4, 0.2, 0.2, 0.2, 0.2, 0.45, NA, 0.45, 
NA, NA, NA, NA, 0.09, 0.18), InnoCat = c("Produc.", "Produc.", 
"Produc.", "Produc.", "Produc.", "Produc.", "Produc.", "Produc.", 
"Produc.", "Produc.", "Produc.", "Produc.", "Produc.", "Produc.", 
"Produc.", "Produc.", "Produc.", "Produc.", "Produc.", "Produc."
), Label = c("P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8", 
"P9", "P10", "P11", "COOP", "EVEBT", "EMPR", "FA", "GC", "ADMON", 
"INV", "ORG", "TEC")), row.names = c(NA, -20L), class = c("tbl_df", 
"tbl", "data.frame"))

enter image description here


Solution

  • You can convert InnoCat into factor variable with the levels in desired order.

    grado$InnoCat <- factor(grado$InnoCat, levels = c("Produc.", "Proc.", "Org.", "Mark."))
    

    You don't have to reverse the legend then.

    ggplot(grado,aes(Label,Grado,fill=InnoCat))+
      geom_bar(position = "dodge",stat="identity")+
      facet_wrap(~InnoCat,nrow=4, scales = "free_y")+
      coord_trans() +
      scale_fill_manual("Leyenda",
                        values = c(
                          "Mark." = "#d982d4",
                          "Org." = "#667ee8",
                          "Proc." = "#53c24f",
                          "Produc." = "#e6914c"
                        ))
    

    enter image description here