Home > Net >  (R) Graphs in a loop and funktion are empty, even though they work when plottet standalone
(R) Graphs in a loop and funktion are empty, even though they work when plottet standalone

Time:05-20

So, I have a boxplot where i annotate the number of datapoint per plot and significance levels in letters above the plots. When plottet in a normal (?!?) workflow, they take about 1-2 seconds to plot in a X Window System Graphics (X11), the plot gets saved afterwards. When the plot-command is wrapped in a for-loop or called by a function, the X11-window stays empty and gets saved like that.

Here is a minimal example using mtcars, showcasing the same problem. Without context this example does not make sense.

library(ggplot2)
setwd("C:/")
output <- "C:/"

data <- mtcars
data$cyl <- as.factor(data$cyl)

#----normal plotting----

x11()
ggplot(data, aes(x = cyl, y = mpg)) 
  stat_boxplot(geom = "errorbar") 
  geom_boxplot()

savePlot(paste0(output, "example_normal", ".tiff"), type = "tiff")
dev.off()

#----plotting throught a function----

my.plot <- function(x)
{
  x11()
  ggplot(x, aes(x = cyl, y = mpg)) 
    stat_boxplot(geom = "errorbar") 
    geom_boxplot()
  
  savePlot(paste0(output, "example_function", ".tiff"), type = "tiff")
  dev.off()
}

my.plot(data)

Cheers

CodePudding user response:

I had to post a print(ggplot(...)) around it to make it work in a for-loop.

  • Related