4

I need to setup a reporting document in which I loop over items and generate individual graphs. when using R in jupyter i read about display_markdown and display_html using repr and IRDisplay here: How to render LaTeX / HTML in Jupyter (R)? This perfectly does the job of printing Markdown inside a code cell. but unfortunately the order is ruined.

If i do:

library(IRdisplay)
library(repr)
options(repr.vector.quote=FALSE)

for (i in 1:3) {
    print(paste("print before headline in run:",i))

    display_markdown(paste("# Headline in run:",i))

    cars <- c(i, 3, 6, 4, 9)
    plot(cars)   

    print(paste("print after headline in run:",i))
}

the end result in jupyter gets mixed up. the headlines appear above the printed lines and graphs:

loop result of above code

R version 3.2.2 (2015-08-14)

Community
  • 1
  • 1
sektionschef
  • 123
  • 1
  • 8
  • 1
    Isn't this just sweet, sweet justice coming into play for using unmanageable, icky notebooks vs orderly R markdown docs? :-) – hrbrmstr Mar 04 '16 at 05:09
  • 1
    I am a man with needs and desires. Rmarkdown works in this regard but sexy notebooks are so tempting. – sektionschef Mar 04 '16 at 07:15
  • Re why headlines are in front of the "before headline" print: irkernel uses evaluate to execute the code and because of the for loop evaluate only "releases" stdout when it steps outside the loop or on when handling plots (or when calling message/warning). See this PR: https://github.com/hadley/evaluate/pull/62. Currently, you could use message instead of print to force the order of the text elements. But this doesn't explain the order of text and plots :-( For that I opened https://github.com/IRkernel/IRkernel/issues/295 – Jan Katins Apr 11 '16 at 16:47
  • @JanSchulz - thanks! – sektionschef Apr 12 '16 at 20:10

1 Answers1

4

it works if I stick to the display functions of IRdisplay defined here: https://github.com/IRkernel/IRdisplay/blob/master/R/display.R during the loop.

library(IRdisplay)
library(repr)

for (i in 1:3) {
    display(paste("print before headline in run:",i))

    display_markdown(paste("# Headline in run:",i))

    cars <- c(i, 3, 6, 4, 9)

    png(paste("plots_",i,".png", sep=""),width=1480, height=1240, res=120)
       plot(cars, main=as.character(i))
    dev.off()

    display_png(file=paste("plots_",i,".png", sep=""))      

    display(paste("print after headline in run:",i))
}
sektionschef
  • 123
  • 1
  • 8