Home > Software design >  Wrap axis labels in ggplot (including strings specified by labels argument)
Wrap axis labels in ggplot (including strings specified by labels argument)

Time:12-10

I am using the following code:

ggplot(overall_vars, aes(overall_mother_protection))   geom_bar()  
  theme_fivethirtyeight()   
  scale_x_discrete(labels=c('Sangat Setuju', 'Agak Setuju', 'Tidak Setuju atau Tidak Setuju', 
                            'Agak Tidak Setuju', 'Sangat Tidak Setuju'))

to generate the following graph

enter image description here

Obviously I need to wrap that text at the bottom there, which I have done before using something like plot scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) However, I am getting hung up on the syntax here because, unlike in past instances, I am already using the labels argument of the scale_x_discrete() layer to specify a list of names (bc I want these names rather than the 1,2,3,4,5 factors within my dataset).

SO, my main question is: how do I write this code to both specify the label names, and wrap the text of those names.

One possible solution might be to just convert all the factors within my dataset to the corresponding character strings, but I would prefer to avoid this route.

(BONUS: another problem that I have run into that I am about to try to solve is the fact that for some of the variables for which I am creating this plot, there are 0 5's, which correspond to 'Sangat Tidak Setuju', the fifth label. I'd like the plot to show that label as well with no bar above it if possible. If you know how to do this, and want to go ahead and include that in your code for solving my other problem, be my guest!)

CodePudding user response:

you can access and manipulate the breaks like this:

scale_x_discrete(labels = ~ str_wrap(as.character(.x), 10))

CodePudding user response:

You could change the variable to factor in the aes() call, which would free up the label argument. This should also cause the empty level of the factor to show on the x axis if you add drop = FALSE to scale_x_discrete().

library(ggplot2)
library(ggthemes)
library(stringr)

ggplot(
    overall_vars,
    aes(factor(
      overall_mother_protection,
      levels = 1:5,
      labels = c(
        'Sangat Setuju', 
        'Agak Setuju', 
        'Tidak Setuju atau Tidak Setuju', 
        'Agak Tidak Setuju', 
        'Sangat Tidak Setuju'
      )
    ))
  )   
  geom_bar()  
  labs(x = 'overall_mother_protection')  
  theme_fivethirtyeight()   
  scale_x_discrete(
    labels = function(x) str_wrap(x, width = 10),
    drop = FALSE
  )
  • Related