Reorder values ggplot

Hello everyone. I'm a beginner who has the following question.
I have this data frame

data5 = data.frame(Dónde=c("Cusco", "Cusco","Loreto", 
"Loreto", "Piura", "Piura", 
"Ucayali", "Ucayali", "Lima", "Lima"), 
Percepción=c("Respetan", 
"No respetan", "Respetan", "No respetan", "Respetan", "No respetan", 
"Respetan", "No respetan", "Respetan", "No respetan"),
Porcentaje=c(28, 67, 35, 64, 31, 65, 30, 67, 28, 69))

And I made this plot:

e = ggplot(data=data5, aes(x=Dónde, y=Porcentaje, 
fill=Percepción))+
geom_bar(stat="identity", position=position_dodge(),width=0.6)+
ggtitle("Percepción de si grandes empresas respetan o no derechos humanos,
en cuatro departamentos")+labs(y="", x="")+
geom_text(aes(label=scales::percent(Porcentaje, scale = 1, accuracy = 1)), 
vjust=-0.6, color="black", 
position = position_dodge(0.6), size=5)+scale_fill_brewer(palette="Set1")+
theme_minimal()+
theme(plot.title = element_text(color="black", size=15, face="bold"))

The result is a bar chart whose values appear in this order:
Loreto, Ucayali, Lima, Piura, Cusco.
I want to change that order to: Loreto, Piura, Ucayali, Lima, Cusco
How can I solve it.
Thank you in advance.

It looks like you have made some other changes between the first and the second code chunks.

The order is determined by the factor levels of Dónde. If this is not a factor, then it will be alphabetical by default, which it is if these code chunks are run.

To change it to the order you want:

library(ggplot2)

e = ggplot(data=data5, 
           aes(
             x=factor(Dónde, levels = c("Loreto", "Piura", "Ucayali", "Lima", "Cusco")), 
             y=Porcentaje, 
             fill=Percepción)
           ) + 
  geom_bar(stat="identity", position=position_dodge(), width=0.6) + 
  ggtitle("Percepción de si grandes empresas respetan o no derechos humanos, en cuatro departamentos") + 
  labs(y="", x="") + 
  geom_text(aes(label=scales::percent(Porcentaje, scale = 1, accuracy = 1)), 
            vjust=-0.6, color="black", 
            position = position_dodge(0.6), size=5) + 
  scale_fill_brewer(palette="Set1") + 
  theme_minimal() + 
  theme(plot.title = element_text(color="black", size=15, face="bold"))
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

Thank you. It worked.