2

Here is my dataset: https://www.dropbox.com/s/31qvc6miew2qkpp/top_terms.csv?dl=0

top_terms = read.csv("top_terms.csv")
top_terms %>% # take the top terms
          mutate(term = reorder(term, beta)) %>%
          ggplot(aes(term, beta, fill = factor(topic))) +
          geom_col(show.legend = FALSE) +
          facet_wrap(~ topic, scales = "free")
          labs(x = NULL, y = "Beta")
          coord_flip()

Spent some time researching on Google and tried various ways but still cannot get the order fixed. I wanted the terms to be sorted in desc order.

enter image description here

halfer
  • 19,824
  • 17
  • 99
  • 186
yeeen
  • 4,911
  • 11
  • 52
  • 73
  • I'd suggest following Uwe's answer at the dupe. The accepted answer will still work, but it takes more doing. Uwe's answer is updating for current versions of ggplot. – Gregor Thomas Nov 05 '18 at 17:00
  • Okay, reopened. For the record, here's my recommended dupe: [ggplot bar plot with facet-dependent order of categories](https://stackoverflow.com/q/18624394/903061) – Gregor Thomas Nov 05 '18 at 17:11
  • 1
    This might help https://stackoverflow.com/a/52214383/786542 – Tung Nov 05 '18 at 17:19
  • 1
    Thanks guys. I referred to Uwe's soln but it doesn't fully work for me esp he is using data.table while i am using tibble. But i made some adjustment and it works now =D – yeeen Nov 05 '18 at 17:30
  • 1
    Possible duplicate of [How to order data by value within ggplot facets](https://stackoverflow.com/questions/52214071/how-to-order-data-by-value-within-ggplot-facets) – camille Nov 05 '18 at 18:05
  • @Gregor: Thanks Gregor! I added my answer to that question per your suggestion – Tung Nov 05 '18 at 18:16

1 Answers1

3
top_terms$ord <- sprintf("%03i", frank(top_terms, beta, ties.method = "first"))

ggplot(top_terms, aes(ord, beta, fill = factor(topic))) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~ topic, scale = "free", drop=TRUE) +
  scale_x_discrete(
    labels = setNames(as.character(top_terms$term), top_terms$ord)
    ) +
  labs(x = NULL, y = "Beta") +
  coord_flip()
yeeen
  • 4,911
  • 11
  • 52
  • 73