我想在RMarkdown中使用函数test1()获得一个图表。在这个函数中,我使用了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 ```发布于 2019-10-15 09:11:23
您需要在test1函数中告诉R返回哪个对象:
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-10-15 10:34:12
编辑16/10/19:#2我使用一个列表作为解决办法,这可能是一个特定的问题,在这里找到更好的结果。
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() ...。
https://stackoverflow.com/questions/58390932
复制相似问题