Jiaxiang
Jiaxiang

Reputation: 883

In a ggplot object, how to increase the space in the lines of caption

I find there is a temporal way to change the text size of the caption. However, I am just searching for a safer solution. Typically, I go through all arguments in the function theme with caption*, but I cannot find an argument to deal with it.


Here is a reproducible minimal example for the suggestion from @Tung.

The only difference between the 1st figure and the 2nd one is the space width of the two lines in the caption. For my preference, I think one-line width is too wider, how to get it like 50% one-line width.

suppressMessages(library(tidyverse))
mtcars %>% 
    ggplot() +
    aes(mpg, disp) +
    geom_point() -> p
p + 
    labs(caption = 'line1\nline2')

enter image description here

p + 
    labs(caption = 'line1\n\nline2')

enter image description here


I don't use the function reprex to get the output because of this error.

> reprex(si = T)
Rendering reprex...
Error in curl::curl_fetch_memory(url, handle = handle) : 
  Timeout was reached: Connection timed out after 10001 milliseconds

By the way, I cannot use the function reprex with the output picture because of the connection restrictions in China. This issue I talks with @yihui and @jennybc on one GitHub Issue for a long time, it is hard to fix and only to wait for an available one in China. But all code I provide I think is enough to reproduce the figures.


Thanks for the @Gregor 's solution, here is an example to display this idea.

mtcars %>% 
    ggplot() +
    aes(mpg, disp) +
    geom_point() +
    labs(caption = 'line1\nline2') -> p0
# p0
p0 + theme(plot.caption = element_text(lineheight = 1.5)) -> p1
p0 + theme(plot.caption = element_text(lineheight = 2.0)) -> p2
p0 + theme(plot.caption = element_text(lineheight = 3.0)) -> p3
p0 + p1 + p2 + p3 + plot_layout(nrow = 2,byrow = T)

enter image description here

Upvotes: 2

Views: 1502

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

You can adjust the lineheight for the caption text.

p + labs(caption = 'line1\nline2') +
  theme(plot.caption = element_text(lineheight = 1.5))

I think this is equivalent to "line spacing", that is 1 is singlespaced, 2 is doublespaced, etc.

If found the solution by looking at the ?theme help page and searching for "caption". This revealed the plot.caption theme setting, and sad it was element_text. I followed the link to ?element_text and saw the lineheight argument.

enter image description here

Upvotes: 5

Related Questions