Knitr emptyline after \include graphics - r

I have a little question, I'm not sure of the cause, but the following knitr code :
<<toto, echo=FALSE, comment=NA, results='asis'>>=
#Data
a<- c(1:100)
b<- c(100:200)
#Plot1
plot(a)
#Plot2
plot(b)
#
produce this LaTeX code :
\includegraphics[width=\maxwidth]{figure/toto1}
(empty line here)
\includegraphics[width=\maxwidth]{figure/toto2}
(empty line here)
How can I remove this empty line?

Use the chunk option fig.show='hold'.

Related

I have a for loop of qplots, how can you structure the plots individually using LaTeX code e.g adding captions to the plots

\begin{figure}[h]
\centering
<<echo=FALSE>>=
for(i in 2:38){
print(my_plot_function(i))
}
#
\end{figure}
This is my code, but what is happening is that when I compile my PDF I only get the first two plots that fit on the first page and I do not get the rest of the plots.
I would like to have all of the plots on separate pages.
And how would I go about adding captions to each individual plot in the for loop.
\documentclass{article}
\begin{document}
<<echo = FALSE, fig.cap = c("First, Second, Third"), results = "asis">>=
library(ggplot2)
for (i in 1:3) {
print(qplot(x = 1, y = i))
cat("Arbitrary \\LaTeX code! \\clearpage")
}
#
\end{document}
You can use the chunk option fig.cap to add captions to your plots. Note that this will wrap your figure in a figure environment, turning it into a float.
Use the chunk option results="asis" to be able to print arbitrary text (including LaTeX markup) into your document using cat().

Null output when printing heatmap.2 object in rmarkdown

I'm using rmarkdown via R-Studio and want to plot a heatmap by the heatmap.2. When I change the angle of column labels via the strCol option I get a NULL message printed before the heatmap in the output PDF file.
Attached a minimal code reproduce the problem:
{r, message=FALSE,warning=FALSE, echo=FALSE}
require(gplots)
data(mtcars)
x <- as.matrix(mtcars)
heatmap.2(x,srtCol=0)
The PDF look like
Is there any way to remove this NULL from the PDF output?
Try the following modification using capture.output. This did not print NULL for me.
```{r, message=FALSE,warning=FALSE, echo=FALSE}
require(gplots)
data(mtcars)
x <- as.matrix(mtcars)
res <- capture.output(heatmap.2(x,srtCol=0))
```
There may be a better way with some option to heatmap.2 but I didn't see it in the documentation. This was based off of the following SO post Suppress one command's output in R.

new font style for stargazer latex table when using knitr

I want to print a latex table generated with stargazer() in monospaced font, and I want to do it in a reproducible way with knitr (i.e., no manual latex coding). I tried to define an environment called mymono and then wrap the knitr chunk in this environment via \begin{} and \end{}. It does not work; the table prints in the default font style.
\documentclass{article}
\newenvironment{mymono}{\ttfamily}{\par}
\begin{document}
<<lm, echo=FALSE>>=
df <- data.frame(x=1:10, y=rnorm(10))
library(stargazer)
lm1 <- lm(y ~ x ,data=df)
#
% reproducible
\begin{mymono}
<<table_texstyle, echo=FALSE, results='asis', message=FALSE>>=
stargazer(lm1, label="test")
#
\end{mymono}
\end{document}
I don't think there is a font setting in stargazer() except for font.size.
# > sessionInfo()
# R version 3.0.2 (2013-09-25)
# Platform: x86_64-apple-darwin10.8.0 (64-bit)
# other attached packages:
# [1] stargazer_5.1
Even better than wrapping the entire table{} in the new font style would be to wrap just tabular{} so that the caption remains the default style. I don't know if there is a way to insert latex code into the stargazer() output programmatically.
Too long for a comment, so here's a start of an answer. Using the model from the question:
\documentclass{article}
\begin{document}
<<lm, echo=FALSE, message=FALSE, include=FALSE>>=
df <- data.frame(x=1:10, y=rnorm(10))
library(stargazer)
lm1 <- lm(y ~ x ,data=df)
tabular_tt <- function(orig.table) {
library(stringr)
tabular.start <- which(str_detect(orig.table, "begin\\{tabular\\}"))
tabular.end <- which(str_detect(orig.table, "end\\{tabular\\}"))
new.table <- c(orig.table[1:(tabular.start - 1)],
"\\texttt{",
orig.table[tabular.start:tabular.end],
"}",
orig.table[(tabular.end + 1):length(orig.table)])
return(new.table)
}
#
<<print, results='asis', echo=FALSE>>=
cat(tabular_tt(capture.output(stargazer(lm1, label="test"))), sep="\n")
#
\end{document}
You can easily adjust it as necessary. If you're having trouble, I would make sure your target LaTeX syntax is correct by playing with a small toy table in LaTeX only, maybe playing with the tex file generated when you knit.
You may need to make the function cat(new.table, sep = "\n") to get it to get the output correctly into the knitr document.

Rstudio does not make plots with knit Word

I seem to have discovered an odd behaviour with the knit Word command in RStudio
This works:
```{r qplot, fig.width = 6, fig.height=6, message=FALSE}
library(ggplot2)
summary(cars)
qplot(speed, dist, data = cars) + geom_smooth()
````
this does not work
```{r q plot, fig.width = 6, fig.height=6, message=FALSE}
library(ggplot2)
summary(cars)
qplot(speed, dist, data = cars) + geom_smooth()
```
returning this message:
pandoc.exe: Could not find image `./test_files/figure-docx/q%20plot.png', skipping...
The issue seems to be with the name of the chunk (i.e. qplot vs. q plot). When there is a space in the chunk name the plot does not render.
It only seems to affect the rendering of Word documents. Rendering html works fine.
I'm using RStudio 0.98.1028 and R3.1.1 on windows 7.
Has anyone else encountered this behaviour?
update
a space after the chunk name also seems to elicit the same behaviour:
this does not work
```{r q_plot , fig.width = 6, fig.height=6, message=FALSE}
library(ggplot2)
summary(cars)
qplot(speed, dist, data = cars) + geom_smooth()
```
Posting the solution in case someone runs across this in future.
From Ben Bolker in the comments Avoid spaces and periods . in chunk labels and directory names as stated in the knitr documentation http://yihui.name/knitr/options.
This error only seems to affect making plots using knitWord. Code chunks with labels that contain spaces and that don't have plotting commands render normally. knitHTML also seems to work fine regardless of if chunk labels have a space or not.
# Let's make a plot
```{r ugly plot}
plot(btc_prices)
```
should apparently be
# Let's make a plot
```{r ugly_plot}
plot(btc_prices)
```
So no spaces... otherwise you'll waste hours googling and crying.

Printing plots generated in a function using R Markdown in RStudio

I am trying to use the R-Markdown feature in R Studio where I was trying to print plots which are generated inside a function. This is a basic run down example of what I am trying to do.
**Test printing plots generated in a function**
================================================
``` {r fig.width=8, fig.height=4, warning=FALSE, eval=TRUE, message=FALSE, tidy=TRUE, dev='png', echo=FALSE, fig.show='hold', fig.align='center'}
dat <- data.frame(x=c(1:10),y=c(11:20),z=c(21:30),name=rep(c("a","b"),each=5))
library(ggplot2)
ex <- function(data){
plot(data[,1],data[,2])
plot(data[,1],data[,3])
}
for (i in 1:10){
t1 <- rbind(i,ex(dat))
}
t1
```
Those testing this code, please make sure to save it as ".Rmd" file and then run the knithtml() in RStudio toolbar. This code above works absolutely fine with the kind of html output I desire. However when I replace the base plotting function by ggplot based code, I cannot get the knithtml() to produce the ggplot output of the 10 plots that I got like before. The base plot code above is now replaced by the following code
p1 <- ggplot(data=data, aes(x=data[,1],y=data[,2]))
p1 <- p1+geom_point()
p1
Am I missing something very simple here.
VJ
There are two problems in your code:
ggplot doesn't recognize the data x and y data, bacause it works inside the data environment. You should give it the column names directly.
The code in yur loop doesn't make sense. You can't mix a plot with an index... (the reason it works with the base plot is through a side-effect) I've replaced it with the simple plot command.
The following will work:
**Test printing plots generated in a function**
================================================
``` {r fig.width=8, fig.height=4, warning=FALSE, eval=TRUE, message=FALSE, tidy=TRUE, dev='png', echo=FALSE, fig.show='hold', fig.align='center'}
dat <- data.frame(x=c(1:10),y=c(11:20),z=c(21:30),name=rep(c("a","b"),each=5))
library(ggplot2)
ex <- function(data){
p1 <- ggplot(data=data, aes(x=x,y=y))
p1 <- p1+geom_point()
return(p1)
}
for (i in 1:2){
plot(ex(dat))
}
```

Resources