how to fix axis text overlap issue in ggplot when using scale_x_continuous

Viewed 239

I'm plotting barchart of top words and their contribution in order facet by topics. In order to order the words in each facet by their contribution, I need to create a variable order and later replace with new labels.

My code is below:

library(ggplot2)    
dat = data.frame(topic = paste('Topic', rep(1:2, each=3)),
               term = c('apple', 'orange', 'peach', 'grape', 'fruit', 'mellon'),
               order = rep(1:3, 2),
               contribution = c(0.01, 0.05, 0.07, 0.02, 0.05, 0.08))

dat %>%
      ggplot(aes(x=order, y=contribution, fill=topic))+
      geom_bar(stat='identity', width=0.5)+
      facet_wrap(~topic, scales = 'free')+
      scale_x_continuous(
            breaks = dat$order,
            labels = dat$term,
            expand = c(0,0)
          ) +
      coord_flip()+
      theme(legend.position = "none")

Surprisingly, I found my y-axis text have some kind of overlaping with other text. Does anyone know why? I spent hours but could not understand why that happens. Thanks a lot!

1 Answers

It's a problem with the fact that there are multiple fruits per order and it's labeling both topics with that have the same order. (i.e. "apple" and "grape"), I suggest using library(forcats) to plot by fruit and reorder them based on order. Here is the code below:

library(ggplot2)    
library(dplyr)
library(forcats)

dat = data.frame(topic = paste('Topic', rep(1:2, each=3)),
                 term = c('apple', 'orange', 'peach', 'grape', 'fruit', 'mellon'),
                 order = rep(1:3, 2),
                 contribution = c(0.01, 0.05, 0.07, 0.02, 0.05, 0.08))

dat %>%
    ggplot(aes(x = fct_reorder(term, order, max), y = contribution, fill = topic)) + 
    geom_bar(stat = 'identity') + 
    facet_wrap(~ topic, scales = "free") + 
    coord_flip()

Created on 2019-07-01 by the reprex package (v0.2.1)

Related