11

I am trying to reduce the space between my long axis labels. In base R graphics I would use lheight, but is seems to have no effect in ggplot. Is there a ggplot equivalent?

Toy example to show the problem:

library("tidyverse")
df0 <- mtcars %>% 
  rownames_to_column("car") %>%
  mutate(car = str_wrap(car, width = 10))

ggplot(data = df0, aes(x = car, y = mpg)) +
  geom_bar(stat = "identity") +
  coord_flip()

# has no effect
par(lheight = 0.5)
ggplot(data = df0, aes(x = car, y = mpg)) +
  geom_bar(stat = "identity") +
  coord_flip()

enter image description here

4
  • 3
    See ggsave, png/jpg and/or specify the size of the text with theme(axis.text = element_text(size=..)
    – Jaap
    Commented Sep 27, 2016 at 10:14
  • @ProcrastinatusMaximus As I understand it that will decease the size of the text (and the space between the lines) rather than than just the size of the space between the lines? ...which is what I am after.
    – guyabel
    Commented Sep 27, 2016 at 10:21
  • If we are after "avoid overlap", we could left align multiple line names, and right align single line names?
    – zx8754
    Commented Sep 27, 2016 at 10:26
  • Similar to this one: padwrap <- function
    – zx8754
    Commented Sep 27, 2016 at 10:38

3 Answers 3

22

You may be looking for a combination of options. The closest to lheight is likely setting lineheight in element_text. I also made the font smaller, just to show options.

ggplot(data = df0, aes(x = car, y = mpg)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  theme(axis.text.y = element_text(lineheight = 0.5, 
                                   size = 6))

enter image description here

0

I had a same problem and I found a solution in reducing my list with: slice(1:40)

library("tidyverse")
df0 <- mtcars %>% 
  rownames_to_column("car") %>%
  mutate(car = str_wrap(car, width = 10)) %>% slice(1:40)

ggplot(data = df0, aes(x = car, y = mpg)) +
  geom_bar(stat = "identity") +
  coord_flip()

# has no effect
par(lheight = 0.6)
ggplot(data = df0, aes(x = car, y = mpg)) +
  geom_bar(stat = "identity") +
  coord_flip()

ggplot(data = df0, aes(x = car, y = mpg)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  theme(axis.text.y = element_text(lineheight = 0.6, size = 5))
0

Another option is using guide_axis with n.dodge in scale_y_discrete to automatically dodge the labels like this:

library("tidyverse")
df0 <- mtcars %>% 
  rownames_to_column("car") %>%
  mutate(car = str_wrap(car, width = 10))

ggplot(data = df0, aes(x = car, y = mpg)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  scale_y_discrete(guide = guide_axis(n.dodge = 2)) +
  theme(axis.text.y = element_text(size = 5))

Created on 2022-10-20 with reprex v2.0.2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.