Printing graphs generated in functions using R Markdown in RStudio

I am trying to use the R-Markdown function in R Studio, where I tried to print the graphs that are generated inside the function. This is a simple example I'm 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 who test this code, be sure to save it as a ".Rmd" file, and then run knithtml () in the RStudio toolbar. This code above works absolutely fine with the kind of html output I want. However, when I replace the basic charting function based on ggplot code, I cannot get knithtml () to create the ggplot output from the 10 charts that I got as before. The following base chart code is now replaced by the following code

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

I miss something very simple here.

V.Ya.

+6
source share
1 answer

There are two problems in the code:

  • ggplot does not recognize data data x and y, because it works inside the data environment. You must give it the column names directly.
  • The code in the yur loop makes no sense. You cannot mix the plot with the index ... (the reason it works with the base chart is a side effect) I 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)) } ``` 
+5
source

Source: https://habr.com/ru/post/920237/


All Articles