ggplot2重新排序多个组

时间:2018-12-26 00:07:49

标签: r ggplot2

我有四个小词,由记号和相似性组成。

    # 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

要分组的源代码

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))

当我尝试绘制四组时,图形混乱: enter image description here

如何重新排序图形?

2 个答案:

答案 0 :(得分:1)

尝试:

{{1}}

答案 1 :(得分:1)

如@Tung所指出的那样,解决方案在于此link

最终源代码:

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")
相关问题