Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R creating a function with a graph

I have a code creates plots that works:

 library(ggplot2)
    x <- Data$V7[c(TRUE, FALSE)]
    y <- Data$V8[c(TRUE, FALSE)]
    
        x <- x[-1]
        y = y[-1]
        df <- data.frame(x = as.numeric(sub(',', '.', x)), y = as.numeric(sub(',', '.', y)))
        
        df$V6 <- factor(df$V6)
        ggplot (df, aes (x, y)) + 
          geom_point(aes(color = V6, shape = V6)) + 
          xlab ("x") + 
          ylab ("y") + 
          geom_abline(slope = 1, linetype = 2, color = "black") +
          facet_wrap(vars(V6)) + 
          theme_bw()

I would like to convert it into a function that, in addition to what in the code above, saves charts in the form of a pdf file.

I don’t really know how to do it, especially with adding a pdf file creation, so please help me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Something like this?

library(ggplot2)

funPlot <- function(Data, filename) {
  x <- Data$V7[c(TRUE, FALSE)]
  y <- Data$V8[c(TRUE, FALSE)]
  
  x <- x[-1]
  y = y[-1]
  df <- data.frame(x = as.numeric(sub(',', '.', x)), y = as.numeric(sub(',', '.', y)))
  
  df$V6 <- factor(df$V6)
  p <- ggplot (df, aes (x, y)) + 
    geom_point(aes(color = V6, shape = V6)) + 
    xlab ("x") + 
    ylab ("y") + 
    geom_abline(slope = 1, linetype = 2, color = "black") +
    facet_wrap(vars(V6)) + 
    theme_bw()
  
  pdf(filename)
  plot(p)
  dev.off()
  p
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading