Embeded Plots Missing when Knitting to PDF - r

I know this question has been asked in different formats, but when searching I couldn't find a solution or problem similar to mine.
Using Mac with RStudio (Version 1.0.153 ) R (version 3.4.3 (2017-11-30) -- "Kite-Eating Tree")
I am just trying to knit to a PDF (weave using knitr) in R markdown, but when I do, the plots are missing. When I knit to HTML the plots are there. I am using the earlywarnings package which helps create the plots. See example below using R markdown:
```{r, earlywarnings, fig.keep='all'}
library(earlywarnings)
data("foldbif")
x = foldbif
plot.ts(x)
```
That plot shows in the pdf output, but not when I create other plots like these:
```{r, echo=FALSE,results='hide',fig.keep='all', fig=TRUE}
out<-generic_ews(x,winsize=50,detrending="gaussian",
bandwidth=5,logtransform=FALSE,interpolate=FALSE)
```
or this one:
```{r, echo=FALSE, results='hide', fig.keep='all', fig=TRUE, warning=FALSE}
qda = qda_ews(x, param = NULL, winsize = 50, detrending = "gaussian",
bandwidth = NULL, boots = 100,s_level = 0.05, cutoff = 0.05,
detection.threshold = 0.002, grid.size = 50, logtransform = FALSE, interpolate = FALSE)
```
The last function also only displays 2 out of 3 plots, but I'll figure that out another time.
Any help would be appreciated. Please let me know if this was not clear.

I can confirm that the issue is related with the use of dev.new(). I copy-pasted the code of the function, removed it (the one line 136 of the function) and it worked, i.e. I get the figure on my pdf. There may be a way to call a function to avoid the effect of dev.new() that I am not aware of.

Related

R, generate pretty plot by dfSummary

I have a problem using summarytools packet. There is tutorial:https://cran.r-project.org/web/packages/summarytools/vignettes/Introduction.html with pretty plots of data:
My problem is that my code generate only TEXT GRAPH. This is chunk of code in my markdown to generate plot:
```{r summary, results='markup'}
library(summarytools)
my_data <- ...
dfSummary(my_data)
```
Unfortunately it generates something like this:
How can I generate this pretty report using summarytools?
Or have you better tools for this? (generate graph, mean, std, etc.)
I found the correct syntax to generate plot:
print(dfSummary(baseline_train), method = 'render')
And the results look like this:
A little update on this:
Always use knitr chunk option results='asis', as someone pointed in an earlier comment.
It is possible to generate summaries including png graphs using print():
print(dfSummary(iris), method = "render")
Starting with version 0.9.0 (available only on GitHub as of Feb. 2019), markdown summaries will also include png graphs provided you specify the following arguments:
plain.ascii = FALSE
style = "grid"
a physical location for temporary png's (tmp.img.dir)
dfSummary(iris, plain.ascii = FALSE, style = "grid", tmp.img.dir = "/tmp")
Additionnal tips
In both cases, you will (in all likelihood) need to adjust the size of the graphs with dfSummary()'s graph.magnif parameter (try values between .75 and .85).
Exclude a column or two to avoid overly wide summaries:
dfSummary(iris, [...], varnumbers = FALSE, valid.col = FALSE)
You need to use results = 'asis' for the code chunk. Here is minimal reproducible example:
---
title: "Untitled"
output: html_document
---
```{r, results='asis'}
library(summarytools)
dfSummary(iris, plain.ascii = FALSE, style = "grid")
```
produces

Why I get different results when running code in R Markdown with knitr than in R script

I have an R code that I've written which is in a normal .r file, now I want to make a markdown html report so I'm basically running the same code, but in chunks with text in between.
I have the weirdest problem where some code works as it worked in the regular r file, but some code produces different results entirely. For example:
mydata_complete_obs %>% select(-(prom_id:end_a)) %>% select(qualified, everything()) %>%
cor(use = "complete.obs", method = "spearman") %>%
corrplot(type = "lower", method = "circle", diag = F, insig = "pch", addCoef.col = "grey",
p.mat = res1$p, title = "Spearman Correlations")
The above code which produces a corrplot does work and produces the same graph as I get in the .r file, but a simple summary() function gives me different things - the correct output being produced in the .r file and in the markdown report I get all zeroes (min, 1st quartile, median, mean, etc. - all 0!). This is the chunk for the summary():
```{r hists, echo = FALSE, warning = FALSE, message = FALSE, error =
FALSE, results="markup"}
summary(mydata_complete_obs)
```
What can be wrong? I'm loading all the libraries and read in the data from an .rds file in the first chunk, and then later use mydata_complete_obs to produce graphs and summaries. If I understand correctly I don't need to load the data for each chunk separately, because I thought that was the problem.
Ok, I have solved the problem. I had to change the query in the database so that the format of the columns will be INT instead of BIGINT (that's in Impala), then when I read it in R, everything worked and the strange behaviour disappeared.

R Markdown: visNetWork not displayed in html output when using for loops (or functions)

My visNetwork is not displayed at all when the displaying is attempted in a for loop. In a regular R script, I use the print function and it works just fine, but it does not work in an R Markdown document.
Here is a (hopefully) reproducible example:
---
title: "I want my beautiful networks back!"
---
# First example that works
```{r}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
vn <- visNetwork(nodes, edges, width = "100%")
vn # Or print(vn)
```
# When does it not work?
## In a for loop
```{r}
for (i in 1) vn
```
## In a for loop + using print
This will display the network in the Viewer.
```{r}
for (i in 1) print(vn)
```
## And also in functions
Same remark...
```{r}
foo <- function(x) print(x)
foo(vn)
```
I'm using Rstudio version Version 1.1.383 and
here is the result of a sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6
other attached packages:
[1] visNetwork_2.0.2
I just found a little workaround, consisting the following steps:
Save plot as HTML
Include the HTML code in RMD file
Here an example:
```{r}
for (i in 1:3){
visSave(vn, file = paste0("test",i,".html"))
}
```
```{r, results='asis'}
for (i in 1:3){
cat(htmltools::includeHTML(paste0("test",i,".html")))
}
```
Another solution is to use print(htmltools::tagList())
This prevents the !DOCTOOLS showing in the output.
```{r}
for (i in 1) print(htmltools::tagList(vn))
```
I came across the same issue / solution when working with Datatables and the solution was provided here by #Yihui: https://github.com/rstudio/DT/issues/67
Edit I've since realised that you need at least one visnetwork plotted outside of the loop, i.e. outside of print(htmltools::taglist()), otherwise the script to render is not added to the html file.
You can remove the !DOCTYPE by operating on the string.
cat (as.character(htmltools::includeHTML(paste0("vn",".html"))) %>%
{gsub("<!DOCTYPE html>","",.,fixed = TRUE)} %>%
{sub("\n","",.)}
)
I had the same problem but also wanted to knit my Rmd from the command line, not within RStudio, to easily generate reports for many different parameters, e.g.:
Rscript -e "rmarkdown::render('graphical-res-vis-reports.Rmd', \
params = list(tissue = '${tissue}'), \
output_file = sprintf('graphical-analysis-results_%s.html','${tissue}'))"
The htmltools::includeHTML(html_path) trick worked well when knitting from within RStudio, but it spat out a pandoc error when I tried to knit it from the command line because it's effectively concatenating multiple standalone HTMLs, which does not result in a valid HTML format. (EDIT: the pandoc error may have also been because R from the command line was using a much older version of pandoc than RStudio, but using iframes is still much cleaner.)
I finally found a solution using iframes that works well. Here is a minimal reproducible example:
---
title: "Finally, a way to print visNetworks in a loop!"
---
```{r make networks}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
html_list <- c()
for (i in 1:3){
vn <- visNetwork(nodes, edges)
outfile <- sprintf("vn_%s.html", i)
visSave(vn, file=outfile)
html_list <- c(html_list, outfile)
}
```
```{r plot networks, results="asis"}
for (i in html_list){
print(htmltools::tags$iframe(title = "My embedded document",
src = f, height = "650", width = "900", frameBorder = "0"))
}
```
EDIT: Note that changing the iframe height and width doesn't resize the object from the HTML file. However, you can increase the size of the visNetwork HTML object with a simple text replacement. In this example, I remove the whitespace padding and change the size from 960x500 to 960x960:
visSave(v1, file = out_html)
# adjust browser window size
cmd = sprintf('sed -i \'s|"browser":{"width":960,"height":500,"padding":40,"fill":false}|"browser":{"width":960,"height":960,"padding":0,"fill":false}|\' %s', out_html)
system(cmd)

How do I make plots appear in a knitr vignette using dev.new()?

My package produces a number of graphs, often more than one at once.
Using x11 or windows devices there is no problem, knitr builds the vignette with images included.
However a requirement of submission to the CRAN repository is the use of dev.new for platform independent plotting. If I replace x11 or windows with dev.new then no images appear in my vignette.
Is there a solution to this? At first I thought this was related to plotting in RStudio but use of the new argument dev.new(noRStudioGD = FALSE) did not help. Additionally building the package from the command line did not solve the problem.
Cheers,
Tom
(Windows 7 x64)
(R 3.1.1)
(RStudio 0.98.507)
The short answer is, you do not use dev.new() at all (or dev.off() or dev.whatever...). If you want a longer answer, please include a minimal reproducible example demonstrating what your problem really is.
I had the same difficulty.
Here's one approach that worked:
p1 <- function(x, knitr=FALSE){
plot(x)
if(!knitr) dev.new()
plot(x^2)
}
The argument knitr= is only used in vignette building.
Now, in the .Rnw file in /vignettes put something like:
%\VignetteEngine{knitr::knitr}
%\VignetteIndexEntry{p1}
\documentclass{article}
\begin{document}
<<setup, include=FALSE>>=
library("knitr")
### Set global chunk options
opts_chunk$set(eval=TRUE,
## text results
echo=TRUE,
results=c('markup', 'asis', 'hold', 'hide')[1],
## plots
fig.path=c('figure', 'figure/minimal-')[1],
fig.keep=c('high', 'none', 'all', 'first', 'last')[1],
fig.align=c('center', 'left', 'right', 'default')[1],
fig.show=c('hold', 'asis', 'animate', 'hide')[1],
dev=c('pdf', 'png', 'tikz')[1],
fig.width=7, fig.height=7, #inches
fig.env=c('figure', 'marginfigure')[1],
fig.pos=c('', 'h', 't', 'b', 'p', 'H')[1]
)
#
<<plot1>>
library("myPackage")
x <- seq(10)
p1(x, knitr=TRUE)
#
\end{document}

2 Knitr/R Markdown/Rstudio issues: Highcharts and Morris.js

I'm presently trying to replicate a few different types of rCharts using my own data. The first is a HighCharts graph with the following code:
````{r}
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8a.csv")`
require(slidify)
require(rCharts)
require(rHighcharts)
```
```{r}
x<-data.frame(blah,stringsAsFactors=TRUE)
colnames(x)<-substr(colnames(x),2,5)
a<-rHighcharts:::Chart$new()
a$chart(type="column")
a$title(text="Percent of Students on Grade Level on G8 FCAT for Reading (1), Math (2), Writing (3), and Science (4)")
a$xAxis(categories=rownames(x))
a$yAxis(title=list(text="Percent Proficient"))
a$data(x)
```
When this is run as a chunk, the graph is produced nicely, but when I use Knit HTML in markdown, it sticks at the preview stage for a while and when I terminate it, it gives a "status 15" message, which I'm unclear what that means and how it should be resolved.
A second graph I'm trying is a Morris.js graph in Markdown with knitr. I took my R code and put into R Markdown which looks like:
```{r}
library(slidify)
library(knitr)
library(rCharts)
library(RColorBrewer)
library(reshape2)
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8.csv")
blah
```
```{r}
m2<-mPlot(x="year",y=colnames(blah)[-1],data=blah, type="Bar")
m2$set(barColors=brewer.pal(4,"Spectral"))
m2$set(xlab="Year")
m2$set(postUnits="%")
m2$set(hideHover="auto")
m2
```
When I run the chunks, it produces a nice graph the way I expected with an html file of (file:///C:/Users/ypetscher/AppData/Local/Temp/RtmpW4q3ka/filed284f137718.html); however, when I click on Knit HTML, I obtain a file which includes the code, but doesn't produce the graph. Additionally, when Google Chrome comes up I receive an error of :
"No webpage was found for the web address:
file:///C:/Users/YPETSC~1/AppData/Local/Temp/Rtmpk1Pfbp/filee0c383670e0.html
Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be
found."
Any help would be greatly appreciated in diagnosing these issues. Thank you much!
NOTE: This is the same solution I posted in the knitr google group.
To get rCharts to work with knit2html, you will need to use the print method with the argument include_assets = TRUE. This is because knitr will not add the js and css assets required by an rCharts plot automatically. Here is a minimal working example.
## MorrisJS with Knit2HTML
```{r results = 'asis', comment = NA}
require(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE)
```
Note that you need to use m1$print('chart2', include_assets = TRUE, cdn = TRUE) if you intend to publish your chart on RPubs, for otherwise the JS and CSS assets will be served from your local library.
Hope this helps.

Resources