Change alphabetical order in ggplot R

997 Views Asked by At

I'm trying to create a line plot with the order that I gave to it in the dataframes I'm using, however I've tried everyting and whener I add something like reorder or stat = "identity" it shows errors, so, can someone help me?

#Create first data frame w/ women's information
df <- data.frame(Ocupacion=c("Estudiantes", "Licenciados/as",
                        "Predoctorales", "Doctores/as", "Profesores/as", 
                        "Catedraticos/as"),
                 Porcentaje=c(54.3, 60.2, 51, 49, 36.1, 14.1),
                 Gender=(c("% Mujeres")))


head(df)


#Create second data frame w/ men's information
df2 <- data.frame(Ocupacion=rep(c("Estudiantes", "Licenciados/as",
                             "Predoctorales", "Doctores/as", "Profesores/as", 
                             "Catedraticos/as"),1),
                  Porcentaje=c(45.3, 39.2, 50.7, 51, 61.2, 82),
                  Gender=(c("% Hombres")))


head(df2)

#Bind both data frames into one to create the graph
df3 <- rbind(df, df2)



# Change line types by groups (gender)

library(ggplot2)
ggplot(df3, aes(x=Ocupacion, y=Porcentaje, group=Gender)) +
  geom_line(stat = "identity", aes(linetype=Gender))+
  theme_bw() +
  ggtitle("Figura 2: Porcentaje de las mujeres y hombres en las universidades
          públicas españolas 2005-2007") +
  theme(plot.title = element_text(hjust = 0.5))+
  geom_point()
1

There are 1 best solutions below

1
On

You need to make "Gender" a factor and enter the order you want to use as levels.

#Create first data frame w/ women's information
df <- data.frame(Ocupacion=c("Estudiantes", "Licenciados/as",
                             "Predoctorales", "Doctores/as", "Profesores/as", 
                             "Catedraticos/as"),
                 Porcentaje=c(54.3, 60.2, 51, 49, 36.1, 14.1),
                 Gender=(c("% Mujeres")))


head(df)


#Create second data frame w/ men's information
df2 <- data.frame(Ocupacion=rep(c("Estudiantes", "Licenciados/as",
                                  "Predoctorales", "Doctores/as", "Profesores/as", 
                                  "Catedraticos/as"),1),
                  Porcentaje=c(45.3, 39.2, 50.7, 51, 61.2, 82),
                  Gender=(c("% Hombres")))


head(df2)

#Bind both data frames into one to create the graph
df3 <- rbind(df, df2) 

df3$Gender <-factor(df3$Gender, levels = c("% Mujeres",
                                           "% Hombres"))



# Change line types by groups (gender)

library(ggplot2)
ggplot(df3, aes(x=Ocupacion, y=Porcentaje, group=Gender)) +
  geom_line(stat = "identity", aes(linetype=Gender))+
  theme_bw() +
  ggtitle("Figura 2: Porcentaje de las mujeres y hombres en las universidades
          públicas españolas 2005-2007") +
  theme(plot.title = element_text(hjust = 0.5))+
  geom_point()