10

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

guyabel
  • 8,014
  • 6
  • 57
  • 86
  • 3
    See `ggsave`, `png`/`jpg` and/or specify the size of the text with `theme(axis.text = element_text(size=..)` – Jaap Sep 27 '16 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 Sep 27 '16 at 10:21
  • If we are after "avoid overlap", we could left align multiple line names, and right align single line names? – zx8754 Sep 27 '16 at 10:26
  • Similar to this one: [padwrap <- function](http://stackoverflow.com/a/34750931/680068) – zx8754 Sep 27 '16 at 10:38

3 Answers3

21

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

tjebo
  • 21,977
  • 7
  • 58
  • 94
Mark Peterson
  • 9,370
  • 2
  • 25
  • 48
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))
Anya Sti
  • 131
  • 2
  • 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

Quinten
  • 35,235
  • 5
  • 20
  • 53