Make more room for lables in ggplot in r

67 views Asked by At

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.

2

There are 2 answers

2
Ronak Shah On BEST ANSWER

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.

0
nathan liang On

I would just extend the y-axis with ylim()—you're not cutting off any data points, so just adjust accordingly:

library(dplyr)
library(ggplot2)
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 = dplyr::if_else(z > 0, 1, -0.2)) |>
  ggplot2::ggplot(ggplot2::aes(x, y, .desc = T), y) +
  ggplot2::geom_col() +
  ggplot2::geom_text(
    ggplot2::aes(
      label = paste0(abs(y), " ", "abcdef"), 
      hjust = just_text
    )
  ) +
  ggplot2::ylim(c(-15, 15)) +
  ggplot2::coord_flip() +
  ggplot2::theme(
    axis.text.y = element_text(
      size = 8, 
      lineheight = 1, 
      margin = margin(r = 1, unit = "cm"))
    )