max
max

Reputation: 4521

Sort ggplot facet_wrap by color?

I would like to sort by ggplot facet_wrap by color.

For example, in this demo code, the color corresponds to groups A, B, C. I am looking to have all the red plots next to each other, and same for the blue and green plots.

I tried sorting my data by group but ggplot seems to switch the order when plotting.

library(tidyverse)
set.seed(42)

# Generate example data frame
id <- 1:15
data <- map(id, ~rnorm(10))
date <- map(id, ~1:10)
group <- map_chr(id, ~sample(c('a','b','c'), size=1))
df <- tibble(id=id, data=data, date=date, group=group) %>% unnest(cols = c(data, date))

# Generate plot
df %>%
  arrange(group) %>%
  ggplot(mapping = aes(x=date, y=data, color=group)) +
  geom_line() +
  geom_point() +
  facet_wrap(~ id)

enter image description here

Upvotes: 2

Views: 491

Answers (2)

Duck
Duck

Reputation: 39595

This could help:

library(tidyverse)
set.seed(42)

# Generate example data frame
id <- 1:15
data <- map(id, ~rnorm(10))
date <- map(id, ~1:10)
group <- map_chr(id, ~sample(c('a','b','c'), size=1))
df <- tibble(id=id, data=data, date=date, group=group) %>% unnest(cols = c(data, date))

df2 <- df %>% mutate(id=factor(id))%>%
  group_by(group) %>%
  mutate(N = n()) %>%
  ungroup() %>%
  mutate(id = fct_reorder(id, N))

# Generate plot
df2 %>%
  arrange(group) %>%
  ggplot(mapping = aes(x=date, y=data, color=group)) +
  geom_line() +
  geom_point() +
  facet_wrap(~ id)

enter image description here

Upvotes: 3

Ahorn
Ahorn

Reputation: 3876

This would be a way (would have to get rid of the double title though):

df %>%
  arrange(group) %>%
  ggplot(mapping = aes(x=date, y=data, color=group)) +
  geom_line() +
  geom_point() +
  facet_wrap(~ group + id)

enter image description here

Upvotes: 1

Related Questions