r:R Markdown不会渲染多个图

时间:2019-06-06 02:28:48

标签: r ggplot2 r-markdown ggplotly slidy

我创建了一个函数,该函数以编程方式生成用于预建模数据查看的必要图表。

我的目标是在R Markdown中运行它们来创建演示文稿,但是,当我尝试创建html_documentslidy_presentationioslides_presentation时,它们不会在输出。

查看功能代码(该功能在RStudio中运行时有效):

data_review<- function(df, dateVar, depVar, indVars){
  for (i in indVars){
    scale_factor<- max(df[depVar])/max(df[i])
    cols <- c("Dependent" = "skyblue", "Independent" = "black")
    print(plotly::ggplotly(ggplot2::ggplot(df, ggplot2::aes(x= !!as.name(dateVar))) +
                         ggplot2::geom_line(ggplot2::aes(y= !!as.name(depVar), color= 'Dependent')) +
                         ggplot2::geom_line(ggplot2::aes(y= !!as.name(i)*scale_factor, color= "Independent")) +
                         ggplot2::scale_colour_manual(name= 'Variables', values=cols) +
                         ggplot2::ylab(depVar) +
                         ggplot2::xlab(toupper(dateVar)) +
                         ggplot2::ggtitle(label = paste(depVar, 'vs.', i, sep = ' '))))
  }
}

以及相应的数据:

df<- data.frame(date= seq(as.Date('2019-01-01'),as.Date('2019-01-10'),'days'), 
                sales= rnorm(n = 10, mean = 5, sd = 1),
                y1= rnorm(n = 10, mean = 6, sd = 2), 
                y2= rnorm(n = 10, mean = 3, sd = 1),
                y3= rnorm(n = 10, mean = 5, sd = 1)
                )

在Studio中运行

data_review(df = df, dateVar = 'date', depVar = 'sales', indVars = c('y1', 'y2', 'y3'))

<code>data_review</code> output

以R Markdown运行(slidy_presentation示例)

没有图表显示,只有代码: output in r markdown

如何获取要渲染的图?

1 个答案:

答案 0 :(得分:1)

这对于创建html文档中的data_review函数有用吗?

data_review<- function(df, dateVar, depVar, indVars){
  plotlist = list()
  for (i in indVars){
    scale_factor<- max(df[depVar])/max(df[i])
    cols <- c("Dependent" = "skyblue", "Independent" = "black")
    p <- ggplot2::ggplot(df, ggplot2::aes(x= !!as.name(dateVar))) +
                             ggplot2::geom_line(ggplot2::aes(y= !!as.name(depVar), color= 'Dependent')) +
                             ggplot2::geom_line(ggplot2::aes(y= !!as.name(i)*scale_factor, color= "Independent")) +
                             ggplot2::scale_colour_manual(name= 'Variables', values=cols) +
                             ggplot2::ylab(depVar) +
                             ggplot2::xlab(toupper(dateVar)) +
                             ggplot2::ggtitle(label = paste(depVar, 'vs.', i, sep = ' '))
    plotlist[[i]] = plotly::ggplotly(p)
  }
  htmltools::tagList(setNames(plotlist, NULL))
}