yeeen
yeeen

Reputation: 4945

ggplot facet chart reorder not working as expected

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

Upvotes: 2

Views: 604

Answers (1)

yeeen
yeeen

Reputation: 4945

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

Upvotes: 3

Related Questions