本文介绍了交互式`ggplotly`图不是从R的`Rmd`文件的`for`循环里面绘制的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我试图在R markdown(循环绘制一系列交互式 ggplotly c> .Rmd )文件。我的 .Rmd 文件的内容: --- 标题:无标题输出:html_document --- $ b $```{r} 图书馆(ggplot2)#地块图书馆(plotly)#for interactive plots #将4个变量转换为因子变量: factor_vars mtcars [factor_vars]< - data.frame(Map(as.factor,mtcars [factor_vars])) for(VAR in factor_vars){ cat(paste(Factor variable:,VAR))#循环内部VAR内容变化p #打印交互式绘图 print(ggplotly(p))} ``` 我推送编织HTML 按钮 RStudio 。不幸的是, .html 文件中没有交互式图。 问题:为什么图表没有绘制?我如何在 Rmd 文件中为循环创建交互式阴谋与结合? p.s。如果我使用 print(p)而不是 print(ggplotly(p)), ggplot2 图表出现在结果 .html 文件中。 解决方案基于这个 github问题,您应该可以做到这样的事情: --- 标题:无标题输出:html_document --- ```{r,message = F} 图书馆(ggplot2)#地块图书馆(绘图)#交互式地块 #将4个变量转换为因子变量: factor_vars< - c(vs,am,gear,carb) mtcars [factor_vars]< - data.frame(Map(as.factor,mtcars [factor_vars])) $ b $ plt< - htmltools :: tagList()i for(VAR in factor_vars){ #循环内VAR内容p geom_po int()+ ggtitle(paste(Factor variable:,VAR)) #打印交互式图#添加到列表 plt [[i]]< - as.widget(ggplotly(p))i< - i + 1 } ``` ```{r,echo = F} plt ``` I tried to plot series of interactive ggplotly graphs from inside for loop in R markdown (.Rmd) file. Contents of my .Rmd file:---title: "Untitled"output: html_document---```{r}library(ggplot2) # for plotslibrary(plotly) # for interactive plots# Convert 4 variables to factor variables:factor_vars <- c("vs", "am", "gear", "carb")mtcars[factor_vars] <- data.frame(Map(as.factor, mtcars[factor_vars]))for (VAR in factor_vars) { cat(paste("Factor variable:", VAR)) # Contents of "VAR" changes inside the loop p <- ggplot(mtcars, aes_string(x = "mpg", y = "wt", color = VAR)) + geom_point() # Print an interactive plot print(ggplotly(p))}```I push Knit HTML button in RStudio. Unfortunately, none of interactive plots appear in the .html file.Question: why the graphs aren't plotted? And how can I create interactive plot in combination with for loop in Rmd file?p.s. If I use print(p) instead of print(ggplotly(p)), ggplot2 plots appear in resulting .html file. 解决方案 Based on this github issue, you should be able to do something like this: --- title: "Untitled" output: html_document --- ```{r, message = F} library(ggplot2) # for plots library(plotly) # for interactive plots # Convert 4 variables to factor variables: factor_vars <- c("vs", "am", "gear", "carb") mtcars[factor_vars] <- data.frame(Map(as.factor, mtcars[factor_vars])) plt <- htmltools::tagList() i <- 1 for (VAR in factor_vars) { # Contents of "VAR" changes inside the loop p <- ggplot(mtcars, aes_string(x = "mpg", y = "wt", color = VAR)) + geom_point() + ggtitle(paste("Factor variable:", VAR)) # Print an interactive plot # Add to list plt[[i]] <- as.widget(ggplotly(p)) i <- i + 1 } ``` ```{r, echo = F} plt ``` 这篇关于交互式`ggplotly`图不是从R的`Rmd`文件的`for`循环里面绘制的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-11 16:04