r-lib / svglite

A lightweight svg graphics device for R
https://svglite.r-lib.org
180 stars 39 forks source link

Svgstring not working in an if-else statement #116

Closed kurpav00 closed 4 years ago

kurpav00 commented 4 years ago

Hello.

I am experiencing a weird bug when using the svgstring function. If I run the following code, a string representation of the resulting chart in svg format gets printed to the console as expected:

library(svglite)
library(ggplot2)

variable <- rnorm(1000,10,1)
s <- svgstring()
ggplot() + geom_histogram(aes(x=log10(variable)), bins = 50)
s() # prints the whole xml string
dev.off()

However, if I embed the svgstring call into an if-else statement, the svg string does not get printed:

if(any(variable <= 0)) { 
  s <- svgstring()
  plot.new()
  text(0.5,0.5,"N.A.")
  s()
  dev.off()
} else { # execution goes to this branch
  s <- svgstring()
  ggplot() + geom_histogram(aes(x=log10(variable)), bins = 50)
  s() # prints an empty string
  dev.off()
}

I fail to comprehend why this is happening. I would be very grateful for a way to fix or at least circumvent this issue. The inability to use svgstring in a conditional statement makes it pretty useless...

Thank you in advance for your help.

thomasp85 commented 4 years ago

only the final line of an expression gets automatically printed. In your last example that means that it is the result of dev.off() that gets printed. If you want explicit printing instead of relying on the automatic printing of the REPL you should put the statement in print() (e.g. print(s()))

Note that this has nothing to do with svglite, but is simply standard R behaviour