Knitr: Turning the R chunk figure caption 90 degrees inline Latex - r

Here is my a code to demo what I cannot do. I use an R chunk to make a figure and use out.extra='angle=90' to make the figure post sideways on the page. Now how do I get my caption to go sideways too?
\documentclass{article}
\usepackage{subcaption}
\begin{document}
<<test-plot,echo=FALSE,fig.cap="I would like to be posted sideways under figure, NOT HERE",out.extra='angle=90'>>=
plot(1)
abline(0, 1)
plot(rnorm(10))
for(i in 1:10) {
abline(v = i, lty = 2)
}
#
\end{document}

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().

Removing blank space from code chunks in .RMD (compiling knitr to Beamer pdf)

I am creating slides on RStudio (Version 0.99.903) in an R Markdown .Rmd file, with output set to PDF (Beamer). On several slides, I would like to insert a plot, either below text or alone on a slide, with the code producing the plot not viewable on the screen. However, despite many things I've tried, there is always a space between the end of the text and the start of the figure, presumably where the code chunk would have appeared had I not set echo=FALSE. For example:
---
title: "Untitled"
author: "Math 35"
date: "October 14, 2016"
output: beamer_presentation
---
```{r setup, echo=FALSE, include=FALSE}
knitr::knit_hooks$set(mysize = function(before, options, envir) {
if (before)
return(options$size)
})
knitr::opts_chunk$set(size='\\small')
knitr::opts_chunk$set(warning=FALSE)
knitr::opts_chunk$set(message=FALSE)
knitr::opts_chunk$set(fig.align='center')
```
## Recap from Last Time: Continuous Random Variables
-- Uniform Random Variable $X\sim U(a,b)$
$$f_X(x) = \frac{1}{b-a}, a \leq x \leq b$$
$$E[X] = \frac{a+b}{2}$$
$$Var(X) = \frac{(b-a)^2}{12}$$
```{r, echo=FALSE, fig.height=3, fig.width=3.5}
density <- dunif(x=seq(from=0, to=6, by=0.01), min=1, max=5)
plot(seq(from=0, to=6, by=0.01), density, col="black", type="l", ylim=c(0, 0.5), lwd=4, xlab="X ~ U(1,5)")
lines(c(3,3), c(0,dunif(3, min=1, max=5)), col="red", lwd=2)
text(2.9, 0.1, "E[X]=(1+5)/2 = 3", col="purple")
```
When I "Knit PDF" within R Studio, the slide that is produced has a large blank space between the text and the figure. As a result, the figure doesn't fit on the slide. I would like to remove this blank space so that everything can fit on the slide.
Here are all the code chunk options I've tried that haven't worked:
results='hide' which would ordinarily hide regular command results but still show the figure, but in this case still leaves the blank space.
strip.white=TRUE
tidy=TRUE
fig.keep = 'high'
fig.keep = 'last'
highlight= 'false'
I've also looked at:
http://yihui.name/knitr/demo/output/ which refers to https://github.com/yihui/knitr/issues/231 but since that addresses the problem in a .Rnw file, which I'm unfamiliar with, I couldn't get that solution to work. I tried putting the suggested header at the top of the .Rmd file but "Knit PDF" didn't complete compiling. I probably did it wrong.
I've looked at the R Markdown reference guide which is where I found the various options I tried above.
I've spent now two hours trying to figure out how to get one figure to show up properly on one slide. Any help would be appreciated.
You could play with par(), but part of the problem comes from the latex side. Using a \begin{center}\end{center} environment adds vertical space. You could try to modify the relevant knitr hook, or simply add the centering instruction by hand,
\centering
```{r, echo=FALSE, fig.height=1.5, fig.width=3.5}
density <- dunif(x=seq(from=0, to=6, by=0.01), min=1, max=5)
par(mar=c(2.5,2.5,0.5,0.5), mgp=c(1.5, 0.5, 0), bg="grey95")
plot(seq(from=0, to=6, by=0.01), density, col="black", type="l", ylim=c(0, 0.5), lwd=4, xlab="X ~ U(1,5)")
lines(c(3,3), c(0,dunif(3, min=1, max=5)), col="red", lwd=2)
text(2.9, 0.1, "E[X]=(1+5)/2 = 3", col="purple")
```
Thanks to all who responded. I set the code chunk option out.width='65%' which worked (along with changing the yaxis to extend from 0 to 0.3 rather than 0 to 0.5):
---
title: "Lecture 5 - The Normal Distribution"
output:
beamer_presentation:
highlight: null
---
```{r setup, echo=FALSE, include=FALSE}
knitr::knit_hooks$set(mysize = function(before, options, envir) {
if (before)
return(options$size)
})
knitr::opts_chunk$set(size='\\small')
knitr::opts_chunk$set(echo=TRUE)
knitr::opts_chunk$set(warning=FALSE)
knitr::opts_chunk$set(message=FALSE)
knitr::opts_chunk$set(fig.align='center')
```
## Recap from Last Time: Continuous Random Variables
-- Uniform Random Variable $X\sim U(a,b)$
$$f_X(x) = \frac{1}{b-a}, a \leq x \leq b$$
$$E[X] = \frac{a+b}{2}$$
$$Var(X) = \frac{(b-a)^2}{12}$$
```{r, echo=FALSE,out.width='65%'}
density <- dunif(x=seq(from=0, to=6, by=0.01), min=1, max=5)
plot(seq(from=0, to=6, by=0.01), density, col="black", type="l", ylim=c(0, 0.3), lwd=4, xlab="X ~ U(1,5)")
lines(c(3,3), c(0,dunif(3, min=1, max=5)), col="red", lwd=2)
text(2.9, 0.1, "E[X]=(1+5)/2 = 3", col="purple")
```

Increasing space between plots in rmarkdown

I am trying to plot two figures in one line and I want to increase the space between them. I searched this forum and a few other websites but none of the options I found seems to be working. Changing the mai, mar and oma values moved everything around but the space remains the same. How can I keep the figures as they are now (size wise) but increasing the gap between them?
Here is my code:
```{r echo=FALSE, fig.width=6, fig.height=6}
g.erd <- erdos.renyi.game(100, 150, type="gnm")
par(mfrow = c(1, 2), mai = c(1, 0.1, 0.1, 0.1))
plot(g.erd, layout=layout.circle, vertex.label=NA)
```
```{r echo=FALSE, fig.width=3, fig.height=3.5}
hist(degree(g.erd), xlab="Degree", ylab="Frequency", main="")
par(mfrow = c(1, 1))
```
and here is how my plot looks like right now: http://i.stack.imgur.com/V2Fc7.png
A 'hackish' solution in ggplot2 would be to put extra line spaces before the beginning of your second graph's title with \n like so:
ggtitle("\n\nPlot Title")
You can try adding markdown breaks between each chunk. <br>, like this:
```{r, echo=F}
plot(cars)
```
<br><br><br>
```{r, echo=F}
plot(cars)
```
Before:
After:
You can stack multiple <br> to achieve the desired gap you want.
This approach kind of works. It depends on why you want the different sizes, but you may be able to fiddle with the layout width and height parameters, or the par(mar=c() to get the spacing and size you want. You could also create a layout that have 3 plotting areas, and leave one blank, as a way to try to force the smaller histogram into the desired location (layout.show(layout(matrix(c(1,1,2,3),ncol=2)))).
```{r echo=FALSE, fig.width=6, fig.height=6}
library(igraph)
g.erd <- erdos.renyi.game(100, 150, type="gnm")
layout(matrix(c(1,2), ncol=2), width=c(1,1))
par(mar=c(1,1,1,1))
plot(g.erd, layout=layout.circle, vertex.label=NA)
par(mar=c(10,5,9,1))
hist(degree(g.erd), xlab="Degree", ylab="Frequency", main="")
```
Hope this helps. Good luck.
edit: I've changed the plotting code to approximate equal graph size, but it's just sort of a guess, and other folks might be able to offer a better solution.

How to specify font sizes in plots with multiple plots per page?

When I generate a .pdf file using knitr from within RStudio, single plots exhibit the desired font sizes of axis labels, legend, etc. However, when I use the layout() function to generate multiple sub-plots, these font sizes are reduced. Please see the example code below.
\documentclass[12pt,english,twocolumn]{article}
\begin{document}
<<settings, message=FALSE, echo=FALSE, cache=FALSE>>=
# set tikz default options
opts_chunk$set(
out.width='15cm',
fig.width=5.906, # inch
fig.height=5.906, # inch
dev='tikz',
fig.align='center',
fig.lp='fig:',
fig.env='figure*',
dev.args=list(pointsize=10),
message=FALSE,
echo=FALSE
)
options(tikzDefaultEngine = "pdftex")
#
<<singlePlot, fig.cap="single plot with good font size">>=
par(cex=1)
plot(rnorm(100))
#
<<multiplePlots, fig.cap="multiple plots with fonts being too small">>=
par(cex=1)
layout(matrix(1:9, 3))
for(i in 1:9) plot(rnorm(100))
#
\end{document}
How do I get fonts in the second plot to be of the same size as the ones in the first plot? Thanks!
Oh my, I figured it out by myself just 30 seconds after posting the question...
The trick is to reverse the order of layout() and par() in the second plot, like so:
<<multiplePlots, fig.cap="multiple plots with fonts being just right">>=
layout(matrix(1:9, 3))
par(cex=1)
for(i in 1:9) plot(rnorm(100))
#
This works as expected.
So it seems that layout() calls par() internally to set a new (smaller) character expansion value when setting up multiple plots. Thus setting par(cex=1) before layout had no effect. I had not known this, but it makes sense. Sorry for the unneccessary disturbance.

allowframebreaks in beamer shading box disappear using knitr

I have the following code
\documentclass{beamer}
\begin{document}
<<setup, include=FALSE>>=
opts_chunk$set(out.lines = 4)
opts_chunk$set(size = 'footnotesize')
options(width=60)
knit_hooks$set(document = function(x) {
gsub('\\\\(begin|end)\\{kframe\\}', '', x)
})
#
After I do this, the R source code and output which is supposing to be displayed in a shaded box now disappear. Any idea on how to get the shaded box back?

Resources