Jack
Jack

Reputation: 857

How to order a plot from lowest to highest?

I looked at other threads where this question is answered,but i couldn't adapt the code. I plot the following graph below. I try then to order from lowest to highest according to the blue color (education==3) when time is at 0. I use the following code to create the order.

 country_order <- df %>% 
      filter(education == 3 & time==0) %>%
      arrange(unemployment) %>% 
      ungroup() %>% 
      mutate(order = row_number())        

However, i am not sure how to introduce the new variable order into ggplot to get the ordering i want. Could someone help?

Here is the plot

ggplot(df, aes(y=unemployment, x=time, fill= education)) + 
      geom_col(, color = "black") + 
      facet_wrap(~ country)

enter image description here

Here is the data:

df= structure(list(time = structure(c(2L, 2L, 2L, 1L, 1L, 1L, 2L, 
    2L, 2L, 1L, 1L, 1L), .Label = c("0", "1"), class = "factor"), 
        unemployment = structure(c(25, 35, 40, 10, 20, 70, 20, 25, 
        55, 23, 17, 60), format.stata = "%9.0g"), education = structure(c(1L, 
        2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("1", 
        "2", "3"), class = "factor"), country = structure(c(1, 1, 
        1, 1, 1, 1, 2, 2, 2, 2, 2, 2), format.stata = "%9.0g")), row.names = c(NA, 
    -12L), class = "data.frame")

Upvotes: 1

Views: 757

Answers (1)

arashHaratian
arashHaratian

Reputation: 98

I think you can use fct_reorder() to reorder factor levels of the desired variable by sorting along another variable.

df %>%
ggplot(aes(y=unemployment, x=time, fill= fct_reorder(education, unemployment, .desc = T))) + 
    geom_col(, color = "black") + 
    facet_wrap(~ country)

enter image description here

Upvotes: 1

Related Questions