R Markdown html:绘图的主要和轴标签作为适合搜索功能的文本

R Markdown html: main and axis labels of plots as text suitable for search-function

我想生成一个带有图表的 R markdown html 文档,应该可以通过搜索功能跳转到某个图表(在我的示例中有有 3 个地块,我想在 html-doc 中跳转到主要是“河流”的地块。 我认为,问题是,情节的主要标签和轴标签是图形元素,就像情节本身,而不是文本。所以搜索功能不起作用。

当然可以在每个图之前手动添加文本,但由于我所有的图都是用 for 循环生成的,所以我 don_t 知道该怎么做。

是否有可能在这种 for 循环中包含文本输出,或者是否有其他想法,绘图的主轴或轴标签如何适用于搜索功能?

提前致谢!

---
title: "search function test"
author: "Michel Grün"
date: "last edited `r format(Sys.Date(),'%d.%m.%Y')`"
output: 
  html_document:
    df_print: paged
---


knitr::opts_chunk$set(echo = TRUE,warning = FALSE)




df<-data.frame(x=seq(1,20),
               trees=rnorm(20,4,3),
               mountains=rnorm(20,6,3),
               rivers=rnorm(20,4,4))



for(i in 2:length(colnames(df))){
  plot(df$x,df[,i],
       main=colnames(df)[i],
       xlab=colnames(df)[1],
       ylab=colnames(df)[i])
}

您可以将 svg 设备与 knitr 挂钩结合使用:

---
title: "search function test"
author: "Michel Grün"
date: "last edited `r format(Sys.Date(),'%d.%m.%Y')`"
output: 
  html_document:
  df_print: paged
---

```{r setup}
library(ggplot2)
library(knitr)

# see https://github.com/yihui/knitr/issues/754
local({
  hook_plot <- knit_hooks$get("plot")
  knit_hooks$set(plot = function(x, options) {
    x <- paste(x, collapse = ".")
    if (!grepl("\.svg", x)) {
      return(hook_plot(x, options))
    }
    # read the content of the svg image and write it out without <?xml ... ?>
    paste(readLines(x)[-1], collapse = "\n")
  })
})

opts_chunk$set(echo = TRUE, warning = FALSE, dev = "svglite")


df <- data.frame(
  x = seq(1, 20),
  trees = rnorm(20, 4, 3),
  mountains = rnorm(20, 6, 3),
  rivers = rnorm(20, 4, 4)
)
```

```{r}

for (i in 2:length(colnames(df))) {
  plot(df$x, df[, i],
    main =paste0(colnames(df)[i], " äöα"),
    xlab = colnames(df)[1],
    ylab = colnames(df)[i]
  )
}
```