rknitrr-markdown

RMarkdown doesn't plot a graph in HTML


I've been working on an HTML document with Rmarkdown.

The document has several sp plots and ggplots, and all of them appear in the HTML.

But when I call plotK (which is a function from the stpp package to plot the spatio-temporal inhomogeneous k-function - STIKhat), the plot doesn't appear in the HTML.

Here's a reproducible example for Rmarkdown:

---
title: "Untitled"
output: html_document
---

```{r}
library(stpp)
data(fmd)
data(northcumbria)
FMD<-as.3dpoints(fmd[,1]/1000,fmd[,2]/1000,fmd[,3])
Northcumbria=northcumbria/1000
# estimation of the temporal intensity
Mt<-density(FMD[,3],n=1000)
mut<-Mt$y[findInterval(FMD[,3],Mt$x)]*dim(FMD)[1]
# estimation of the spatial intensity
h<-mse2d(as.points(FMD[,1:2]), Northcumbria, nsmse=50, range=4)
h<-h$h[which.min(h$mse)]
Ms<-kernel2d(as.points(FMD[,1:2]), Northcumbria, h, nx=5000, ny=5000)
atx<-findInterval(x=FMD[,1],vec=Ms$x)
aty<-findInterval(x=FMD[,2],vec=Ms$y)
mhat<-NULL
for(i in 1:length(atx)) mhat<-c(mhat,Ms$z[atx[i],aty[i]])
# estimation of the STIK function
u <- seq(0,10,by=1)
v <- seq(0,15,by=1)
stik1 <- STIKhat(xyt=FMD, s.region=northcumbria/1000,t.region=c(1,200),
                 lambda=mhat*mut/dim(FMD)[1], dist=u, times=v, infectious=TRUE)
```

```{r}
plotK(stik1)
```

After knitting, the plot doesn't appear in the HTML output. Does anyone have any idea what is going on?

Thank you so much!


Solution

  • Try this with some extra packages in your plotting chunk:

    library(png)
    library(grid)
    library(gridExtra)
    
    plotK(stik1)
    dev.print(png, "plot.png", width=480, height=480)
    img <- readPNG("plot.png")
    img <- rasterGrob(img)
    grid.draw(img)