首页 > 解决方案 > r:R Markdown 不渲染多个绘图

问题描述

我创建了一个函数,它以编程方式为预建模Data Review生成必要的图表。

我的目标是在 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> 输出

在 R Markdown 中运行(slidy_presentation示例)

没有图表呈现,只有代码: r markdown 中的输出

我怎样才能得到要渲染的图?

标签: rggplot2r-markdownggplotlyslidy

解决方案


这是否适用于创建 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))
}

推荐阅读