简体   繁体   English

使用RStudio中的R Markdown在函数中生成的打印图

[英]Printing plots generated in a function using R Markdown in RStudio

I am trying to use the R-Markdown feature in R Studio where I was trying to print plots which are generated inside a function. 我试图在R Studio中使用R-Markdown功能,我试图打印在函数内生成的图。 This is a basic run down example of what I am trying to do. 这是我尝试做的一个基本的例子。

**Test printing plots generated in a function**
================================================

``` {r  fig.width=8, fig.height=4, warning=FALSE, eval=TRUE, message=FALSE, tidy=TRUE, dev='png', echo=FALSE, fig.show='hold', fig.align='center'}
dat <- data.frame(x=c(1:10),y=c(11:20),z=c(21:30),name=rep(c("a","b"),each=5))
library(ggplot2)

ex <- function(data){

  plot(data[,1],data[,2])
  plot(data[,1],data[,3])
}

for (i in 1:10){
t1 <- rbind(i,ex(dat))
}
t1
```

Those testing this code, please make sure to save it as ".Rmd" file and then run the knithtml() in RStudio toolbar. 那些测试此代码的人请确保将其保存为“.Rmd”文件,然后在RStudio工具栏中运行knithtml() This code above works absolutely fine with the kind of html output I desire. 上面的代码与我想要的那种html输出完全一致。 However when I replace the base plotting function by ggplot based code, I cannot get the knithtml() to produce the ggplot output of the 10 plots that I got like before. 然而,当我用基于ggplot的代码替换基本绘图功能时,我无法获得knithtml()来生成我之前得到的10个绘图的ggplot输出。 The base plot code above is now replaced by the following code 上面的基本代码现在由以下代码替换

  p1 <- ggplot(data=data, aes(x=data[,1],y=data[,2]))
  p1 <- p1+geom_point()
  p1 

Am I missing something very simple here. 我在这里错过了一些非常简单的事情

VJ VJ

There are two problems in your code: 您的代码中存在两个问题:

  1. ggplot doesn't recognize the data x and y data, bacause it works inside the data environment. ggplot无法识别数据x和y数据,因为它在数据环境中工作。 You should give it the column names directly. 你应该直接给它列名。
  2. The code in yur loop doesn't make sense. 你的循环中的代码没有意义。 You can't mix a plot with an index... (the reason it works with the base plot is through a side-effect) I've replaced it with the simple plot command. 你不能将一个情节与一个指数混合......(它与基础图一起使用的原因是通过副作用)我用简单的绘图命令替换它。

The following will work: 以下将有效:

**Test printing plots generated in a function**
================================================

``` {r  fig.width=8, fig.height=4, warning=FALSE, eval=TRUE, message=FALSE, tidy=TRUE, dev='png', echo=FALSE, fig.show='hold', fig.align='center'}
dat <- data.frame(x=c(1:10),y=c(11:20),z=c(21:30),name=rep(c("a","b"),each=5))
library(ggplot2)

ex <- function(data){
  p1 <- ggplot(data=data, aes(x=x,y=y))
  p1 <- p1+geom_point()
  return(p1) 
}

for (i in 1:2){
plot(ex(dat))
}

```

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM