在ggplot对象中,如何增加标题行中的空间

时间:2019-03-25 11:43:34

标签: r ggplot2

我发现有一种临时的方法可以更改字幕的文本大小。但是,我只是在寻找更安全的解决方案。 通常,我使用theme来遍历函数caption*中的所有参数,但是找不到要处理的参数。


这是@Tung的建议的可复制的最小示例。

第一个图形和第二个图形之间的唯一区别是标题中两行的间距。 就我的喜好而言,我认为单行宽度太宽,如何使其达到50%的单行宽度。

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


由于此错误,我不使用函数reprex来获取输出。

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

顺便说一句,由于中国的连接限制,我无法在输出图片中使用函数reprex。 我在一个GitHub Issue上与@yihui和@jennybc讨论了很长时间,很难修复,只能等待在中国发布。 但是我提供的所有代码都足以重现这些数字。


感谢@Gregor的解决方案,下面是显示此想法的示例。

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

1 个答案:

答案 0 :(得分:2)

您可以调整字幕文本的lineheight

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

我认为这等效于“行距”,即1是单行距,2是双行距,等等。

如果通过查看?theme帮助页面并搜索“标题”找到了解决方案。这显示了plot.caption主题设置,很可惜它是element_text。我点击了指向?element_text的链接,并看到了lineheight的论点。

enter image description here