rggplot2dplyrgeom-text

Make more room for lables in ggplot in r


Is there a way to have this plot squeezed a little so labels of extreme cases (A and G) have could show up completely. enter image description here

code:

x <- LETTERS[1:11]
y <- c(9, 4, 6, 8, 5, 7, -9, -4, -6, -8, -5)
z <- seq(-1, 1, by = 0.2)

dat <- data.frame(x, y, z) |> 
  mutate(just_text = ifelse(z > 0, 1, -0.2))

dat %>%
  ggplot(aes(fct_reorder(x, y, .desc = T), y)) +
  geom_col() +
  geom_text(
    aes(label = paste0(abs(y), " ", "abcdef"), 
        hjust = just_text)) +
  coord_flip() +
  theme(
  axis.text.y = element_text(size = 8, 
                             lineheight = 1, 
                             margin = margin(r = 1, unit = "cm")))

Any help would be appreciated.


Solution

  • You may use expand -

    library(ggplot2)
    
    dat %>%
      ggplot(aes(fct_reorder(x, y, .desc = T), y)) +
      geom_col() +
      geom_text(
        aes(label = paste0(abs(y), " ", "abcdef"), 
            hjust = just_text)) +
      coord_flip() +
      theme(
        axis.text.y = element_text(size = 8, 
                                   lineheight = 1)) + 
      scale_y_continuous(expand = expansion(add = c(5, 5)))
    

    enter image description here

    In this case, I have expanded the axis by 5 units each in both the direction. You may adjust it according to your requirement.