Change facet_wrap order in ggplot2

Asked

Viewed 647 times

7

See the code below, which generates the graph that comes soon after:

library(lme4)
library(ggplot2)
ggplot(sleepstudy, aes(x=Days, y=Reaction)) + 
  geom_point() +
  geom_smooth(method = "lm", se=FALSE, color="black") +
  facet_wrap(~ Subject, nrow=3) 

Exemplo

It shows the reaction time (Reaction) of each subject (308, 309, ..., 372) after a few days with sleep deprivation (Days). Note that each of the panels has a line adjusted to the data, with different inclinations.

I’d like to get a chart similar to this, except for the order of the subjects. I would like them to be ordered not by the ascending order of their numbers, but by the ascending order of the inclination of the lines set within each panel.

For example, I would like the first subject to be 335. The second, 309, and so on.

How can I use ggplot2 to do this?

1 answer

3


Follow a code for this. The ggplot sorts charts according to the order of the variable’s factors Subject, if it is not a factor it converts into factor first.

So what I did here was recreate the variable Subject with the factors ordered by the slope of the regression line.

library(lme4)
library(ggplot2)
library(forcats)
library(dplyr)


obter_beta <- function(y, x){
  coef(lm(y ~ x))[2]
}

sleepstudy %>%
  group_by(Subject) %>%
  mutate(Beta = obter_beta(Reaction, Days)) %>%
  ungroup() %>%
  mutate(Subject = fct_reorder(Subject, Beta)) %>%
  ggplot(aes(x=Days, y=Reaction)) + geom_point() + 
  geom_smooth(method = "lm", se=FALSE, color="black") + 
  facet_wrap(~ Subject, nrow=3) 

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.