【问题标题】:Add a title for each chart created by a loop in knitr为由 knitr 中的循环创建的每个图表添加标题
【发布时间】:2020-09-09 17:44:19
【问题描述】:

如果您运行以下命令来创建 HTML 文档,您会看到它为三种鸢尾花创建了一个单独的条形图。

为了在循环中创建的 HTML 文档中打印此图表列表,您必须将图表存储在列表中并在循环后运行 htmltools 行以使其正确显示;你不能只打印(图表)。

但是,我希望它在打印图表之前简单地打印物种名称。然后同样的下一个等等。这样您就可以知道每个图表代表哪个组。

我知道您可以使用 plot_ly 参数为循环中的每个图表添加标题。但是,我只是将这些条形图用作一个简单的示例;我的实际报告使用了另一个类似的包,它没有直接在图表中包含标题的选项,但以相同的方式工作。这就是为什么我试图弄清楚如何简单地让它打印“setosa”,然后显示条形图,“versicolor”,然后显示条形图等。我不知道如何使用 htmltools 来做到这一点。

---
title: "Test"
output: html_document
---


```{r charts, echo=FALSE, message=FALSE}

library("plotly")

charts<-list()

for(i in 1:length(unique(iris$Species))){

    iris2<-iris[iris$Species==unique(iris$Species)[i],]

    charts[[i]]<-plot_ly(iris2, x = ~Sepal.Length, y = ~Sepal.Width, type = 'bar')
}

htmltools::tagList(charts)
```

这是我正在尝试做的一个示例(仅显示此图像中的第一组):

【问题讨论】:

    标签: r r-markdown plotly knitr r-plotly


    【解决方案1】:

    您可以制作另一个列表并将文本附加到图表中。基本思想是以下代码块:

    list(tags$h1(unique(iris$Species)[i]),
                            tags$figure(charts[[i]]))
    

    您可以检查?taglisttag$... 的参数,以更好地了解这个想法的来源。请看下面的答案:

    ---
    title: "Test"
    output: html_document
    ---
    
    
    ```{r charts, echo=FALSE, message=FALSE}
    
    library("plotly")
    library("htmltools")
    
    charts <- list()
    
    for(i in 1:length(unique(iris$Species))){
    
        iris2 <- iris[iris$Species==unique(iris$Species)[i],]
    
        charts[[i]]<-plot_ly(iris2, x = ~Sepal.Length, y = ~Sepal.Width, type = 'bar')
    }
    
    tgls <- list()
    
    for(i in 1:length(unique(iris$Species))){
      tgls[[i]] <- list(tags$h1(unique(iris$Species)[i]),
                        tags$figure(charts[[i]]))
      }
    
    
    tagList(tgls)
    ```
    

    我不确定你为什么不能使用%&gt;% layout(title="plot title")。您可能想分享您用于灌封的实际包以获得更直接的答案。为了完整起见,我也发布了一个带有plotly 参数的解决方案。

    ---
    title: "Test"
    output: html_document
    ---
    
    
    ```{r charts, echo=FALSE, message=FALSE}
    
    library("plotly")
    
    charts<-list()
    
    for(i in 1:length(unique(iris$Species))){
    
        iris2<-iris[iris$Species==unique(iris$Species)[i],]
    
        charts[[i]]<-plot_ly(iris2, x = ~Sepal.Length, y = ~Sepal.Width, type = 'bar') %>% 
                        layout(title=as.character(unique(iris$Species)[i]))
    }
    
    htmltools::tagList(charts)
    ```
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      相关资源
      最近更新 更多