Marcos Grzeça
Marcos Grzeça

Reputation: 85

ggplot2 reorder multiple groups

I have four tibble composed by token and similarity.

    # A tibble: 15 x 2
   token     similarity
   <chr>          <dbl>
 1 beer           1.000
 2 bud            0.495
 3 answering      0.492
 4 raw            0.489
 5 tequila        0.476
 6 shower         0.468
 7 colors         0.468
 8 flx            0.457
 9 carrots        0.450
10 learn          0.447
11 pong           0.445
12 tall           0.444
13 drinking       0.444
14 brew           0.443
15 anything       0.442

Source code to group

beer %>%
  mutate(selected = "beer") %>%
  bind_rows(alcohol %>%
              mutate(selected = "alcohol")) %>%
  bind_rows(drunk %>%
              mutate(selected = "drunk")) %>%
  bind_rows(sober %>%
              mutate(selected = "sober")) %>%
  group_by(selected) %>%
  top_n(15, similarity) %>%
  ungroup %>%
  mutate(token = reorder(token, similarity)) %>%
  ggplot(aes(token, similarity, fill = selected)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~selected, scales = "free") +
  coord_flip() +
  theme(strip.text=element_text(hjust=0, size=12)) +
  scale_y_continuous(expand = c(0,0))

When I try plot four groups, the graphic is cluttered: enter image description here

How can I reorder the graphic?

Upvotes: 0

Views: 332

Answers (2)

Marcos Grze&#231;a
Marcos Grze&#231;a

Reputation: 85

As pointed out by @Tung, the solution lies in this link.

Final source code:

reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) {
  new_x <- paste(x, within, sep = sep)
  stats::reorder(new_x, by, FUN = fun)
}

scale_x_reordered <- function(..., sep = "___") {
  reg <- paste0(sep, ".+$")
  ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), ...)
}

beer %>%
  mutate(selected = "beer") %>%
  bind_rows(alcohol %>%
              mutate(selected = "alcohol")) %>%
  bind_rows(drunk %>%
              mutate(selected = "drunk")) %>%
  bind_rows(sober %>%
              mutate(selected = "sober")) %>%
  group_by(selected) %>%
  top_n(15, similarity) %>%
  ungroup %>%
  mutate(token = reorder(token, similarity)) %>%
  ggplot(aes(reorder_within(token, similarity, selected), similarity)) +
  geom_segment(aes(xend = reorder_within(token, similarity, selected), yend = 0), 
               colour = "#FF9999") +
  scale_x_reordered() +
  geom_col(show.legend = FALSE) +
  facet_wrap(~selected, scales = "free") +
  coord_flip() +
  xlab("token") +
  theme(strip.text=element_text(hjust=0, size=12)) +
  scale_y_continuous(expand = c(0,0)) +
  geom_bar(stat = "identity")

Upvotes: 1

M_M
M_M

Reputation: 909

Try:

...
ggplot(aes(reorder(token, similarity), similarity, fill = selected)) +
...

Upvotes: 1

Related Questions