I am trying to order a ggplot graph using facet_grid, example:
Sorry , I know that my data its no logic but its ok to show my problem with the facets...
In my real data I dont have this data, only i use this block below to get my data in this example:
################ only to get data in my example ######################
set.seed(12345)
Date <- seq(as.Date("2010/1/1"), as.Date("2013/1/1"), "6 months" )
Y <- rnorm(n=length(Date), mean=100, sd=1)
df <- data.frame(Date, Y)
df$Year <- format(df$Date, "%Y")
df$Sem <- format(df$Date, "%b")
df$Sem <- gsub("ene.", "1S",df$Sem )
df$Sem <- gsub("jul.", "2S",df$Sem )
df$MonthYear <- format(df$Date, "%b-%Y")
############## o #################
Variables that are in my real data are:
Sem, Semester and Y
I extract the year to sort in my second try:
df=df %>%
mutate(extract_year= sub('.*(\\d{4}).*', '\\1', MonthYear))
df$Semester=paste0(df$Sem,df$extract_year)
#Here I tried to sort the facet but I failed:
df2 <- within(df,Semester <- ordered(Semester, levels = rev(sort(unique(Semester)))))
df2 %>%
ggplot(aes(y = Y ))
geom_bar()
facet_grid(Semester~.)
I tried also with:
df2 %>%
arrange(extract_year) %>%
ggplot(aes(y = Y ))
geom_bar()
facet_grid(Semester~.)
I would like get this order:
1S2010/2S2010/1S2011/2S2011/1S2012/2S2012
CodePudding user response:
Basically you have to set the order of the levels in your desired order. One option to achieve that would be to arrange
the data in your desired order and make use of forcats::fct_inorder
to set the order of the levels of your Semester
variable.
library(ggplot2)
library(dplyr)
## Make Semester variable in the desired format
df <- mutate(df, Sem = recode(Sem, Jan = "1S", Jul = "2S"),
Semester = paste0(Sem, Year))
# Arrange and set order
df <- df %>%
arrange(gsub("^(\\dS)(\\d{4})$", "\\2\\1", Semester)) %>%
mutate(Semester = forcats::fct_inorder(Semester))
df %>%
ggplot(aes(y = Y ))
geom_bar()
facet_grid(Semester~.)