RMarkdown - 与 ggplotly 一起使用

RMarkdown - function with ggplotly

我想使用我的函数 test1() 在 RMarkdown 中获取图表。在我使用 cat() 函数和 ggplotly() 的函数中,我发现使用 cat() 是本例中的主要问题。当我使用 cat() 删除所有代码时,我将得到我想要的 (test2())。 但对我来说,使用 cat() 很重要,因为我可以在 test1() 中创建段落和评论。 test1()test_ggplotly.Rmd 我应该改变什么?

test_ggplotly.R

library("ggplot2")
library("plotly")

test1<-function(){

  cat('\n')  
  cat("## Chapter 1", "\n") 
  cat("### Example ", "\n") 
  cat(" Comment ", "\n") 
  cat('\n') 

  p1<-ggplot(mpg, aes(x = displ, y = hwy, color = class)) + geom_point()
  ggplotly(p1)

  cat('\n')   
}


test2<-function(){

  p1<-ggplot(mpg, aes(x = displ, y = hwy, color = class)) + geom_point()
  ggplotly(p1)
}

test_ggplotly.Rmd

---
title: "Test"
author: " "
date: "10/14/2019"
output: html_document
---
``* {r setup, include=FALSE,echo=FALSE}
knitr::opts_chunk$set(echo = TRUE)
``

``{R, echo=FALSE}
source("test_ggplotly.R")
``
``
# Test 1
``{r, results='asis', echo=FALSE}
test1()
``
# Test 2
``{r, results='asis', echo=FALSE}
test2()
``
* should be ```

您需要在 test1 函数中告诉 R return 什么对象:

test1<-function(){

        cat('\n')  
        cat("## Chapter 1", "\n") 
        cat("### Example ", "\n") 
        cat(" Comment ", "\n") 
        cat('\n') 

        p1<-ggplot(mpg, aes(x = displ, y = hwy, color = class)) + geom_point()
        return( ggplotly(p1) )

        cat('\n')
}

编辑 2019 年 16 月 10 日:#2 对于 Rmarkdown,我使用一个列表作为解决方法,这可能是一个特定的问题,所以在这里找到更好的结果。

1 确实忘记了对 plotly::ggploty() 的调用。下面的代码应该显示想要的图表。

让我们重新格式化您的问题:

test1<-function(){
        
        library(ggplot2)
        
        for(i in 1:4){
                cat('\n')
                cat("## Chapter ", i, "\n") 
                cat("### Exampstle ", "\n") 
                cat(" Comment ", "\n") 
                cat('\n') 
                
                p1 <- ggplot(mpg, aes(x = displ, y = hwy, color = class)) + 
                        geom_point() + 
                        ggtitle(paste("Chart nr ", i))
                
                return(p1)
                
                cat('\n') 
        }
}
test1()

如果您只想打印输出,您可以使用 print 而不是返回值:

test1<-function(){
        
        library(ggplot2)

        res <- NULL
        
        for(i in 1:4){
                cat('\n')
                cat("## Chapter ", i, "\n") 
                cat("### Exampstle ", "\n") 
                cat(" Comment ", "\n") 
                cat('\n') 
                
                p1 <- ggplot(mpg, aes(x = displ, y = hwy, color = class)) + 
                        geom_point() + 
                        ggtitle(paste("Chart nr ", i))

                p1 <- plotly::ggplotly( p1 )

                res[[i]] <-p1 
        }
        return(res)
}
my_res <- test1()

my_res[[1]]
my_res[[2]]
my_res[[3]]
my_res[[4]]

否则,将每次迭代存储在一个列表中,例如 p1[[i]] = ggplot() ... 以便稍后调用。