在 R Markdown 中使用 ggplot 生成大图描述

问题描述 投票:0回答:2

我需要有一个长的描述,附加到我的 ggplot 图的底部,左对齐,最好我想直接在 R Markdown 文件中执行此操作。我正在编织 PDF。有没有一个包可以工作来完成这种任务?

这是我试图复制的图形类型: enter image description here

我尝试过的一些事情:

  1. 使用
    labs()
    的标题参数:
ggplot(data, aes(x = x, y = y) +
  geom_point() +
  labs(caption = "Really long figure description")

这不会使文本换行。

  1. 使用
    ggpubr::ggarrange
p <- ggplot(data, aes(x = x, y = y) +
  geom_point() +
ggarrange(p, bottom = "Really long figure description")

这也不会换行文本。

  1. 块头中类似这样的内容:
{r, fig.cap = "\\label{fig:myfigure} Here be your caption text"}
    generate_a_figue(my_data)

这根本不会改变输出。

有没有一种方法可以遵循 R Markdown 精神,避免弄乱 LaTeX 文件?

r ggplot2 r-markdown
2个回答
1
投票

长图形标题有点笨拙,但您可以将完整的内容作为

fig.cap
参数放入头文件中,如下所示。换行效果可以包含两次转义反斜杠:
\\\\

为了获得奖励积分,如果您想将其包含在 TOF 中,可以提供简短的标题:

```{r irisfig, echo=F, fig.cap='First line of a figure caption, \\\\ followed by an incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, long figure caption.'  , fig.scap='Short caption for the TOC'}
library(ggplot2)
ggplot2::ggplot(iris, aes(Sepal.Length, Sepal.Width))+
  geom_point()
```

其产量:

enter image description here


0
投票

几年后...

{ggtext}
是一个很棒的附加包,可以帮助解决此类问题。 它允许使用众所周知的 Rmarkdown 或一些 css 样式跨度来格式化任何主题元素中的文本。

原则上,您将

element_markdown()
添加到
theme()
参数中。 但是,对于较长的文本块,最好使用
element_textbox_simple()
。这封信有一些默认设置,可以让您免于调整太多参数。在下面的示例中,我为文本添加了填充。

请注意,我在 ggplot 之外的单独变量中定义了标题文本,即

caption_text
,其中已经包含 Markdown 和样式标签。
这可以让
labs()
更干净一点。

library(ggplot2)
library(ggtext)

# let's define the long caption outside the call below
caption_text <- "First **line** of a *figure caption*, <br> followed by an incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, <span style='color:blue'>**incredibly blue in bold.**</span>, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, incredibly, long figure caption."

ggplot2::ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point() +
  labs(caption = caption_text) +
  theme(plot.caption = element_markdown())

ggplot2::ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point() +
  labs(caption = caption_text) +
  theme(plot.caption = element_textbox_simple(padding = margin(5.5, 5.5, 5.5, 5.5)))

我跳过第一张图的输出。这表明

element_markdown()
无法处理很长的标题。

第二张图如下所示: ggplot with very long caption formatted with ggtext and its element_textbox_simple() method

© www.soinside.com 2019 - 2024. All rights reserved.