0

I know this question has been asked/answered other places but I am very confused with how/where to apply code to reorder variables on my y-axis in a facet grid.

Data:

df <- data.frame(
  type   = c("Small", "X-large", "Medium", "Large", "Small", "X-large", "Medium", "Large", "Small", "X-large", "Medium", "Large"), 
  group   = c("A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "C", "C"),
  value = c(22, 40, 31, 60, 26, 24, 22, 18, 30, 70, 60, 50)
)

Figure:

plot <- ggplot(df, aes(y=type, size = 15)) + facet_grid(group ~ ., scales="free_y", space="free_y")
plot <- plot + geom_point(aes(x=value),
                    size=3)
plot

enter image description here

What I would like is for the variables on the y-axis for each facet to go in a different order (small, medium, large, x-large) from top to bottom (instead of current order: x-large, small, medium, large). How do I change this? I understand my answer should look something like this: df$new = factor(df$type, levels=c("Small","Medium","Large","X-large"), labels=c("Small","Medium","Large","X-large")) but I am not sure where to put this into my figure code. I tried putting it where 'type' is but that didn't work... Any help wold be greatly appreciated!

clions226
  • 81
  • 1
  • 9
  • 1
    You don't need to change the labels just change the factor levels (`df$type = factor(df$type, levels=c("Small","Medium","Large","X-large"))`) and repeat the same code that you have. – Ronak Shah Jul 06 '21 at 03:27
  • Sorry that this was a duplicate question. Thank you so much @RonakShah, that worked, really appreciate the help! – clions226 Jul 06 '21 at 12:11

1 Answers1

1

This is a duplicate question so it will be closed, but this example should help you understand the problem:

library(tidyverse)

df <- data.frame(
  type   = c("Small", "X-large", "Medium", "Large", "Small", "X-large", "Medium", "Large", "Small", "X-large", "Medium", "Large"), 
  group   = c("A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "C", "C"),
  value = c(22, 40, 31, 60, 26, 24, 22, 18, 30, 70, 60, 50)
)

df$type <- factor(df$type, levels = c("X-large", "Large", "Medium", "Small"))

ggplot(df, aes(y=type, size = 15)) + 
  facet_grid(group ~ ., scales = "free_y", space = "free_y")+
  geom_point(aes(x = value), size = 3)

example_1.png

jared_mamrot
  • 22,354
  • 4
  • 21
  • 46
  • I don't believe that's the right duplicate, the question is about the order of the axis labels, not of the facets. As for the answer, it solves the problem, upvoted. – Rui Barradas Jul 06 '21 at 03:33
  • 1
    Ahh, yes, thanks @RuiBarradas, I got it wrong. Thanks for pointing out my error - [this answer](https://stackoverflow.com/questions/44973678/ordering-y-axis-with-facet) is the duplicate. – jared_mamrot Jul 06 '21 at 03:40
  • Yes! Thank you @RonakShah, I didn't know about community wiki answers. That is exactly what I should have done in this situation - thanks for the help! – jared_mamrot Jul 06 '21 at 23:24