Increasing space between plots in rmarkdown - r

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.

Related

How to reduce (white) margin of a waffle chart?

I' d like to ask some help on how to reduce the amount of white space in a waffle chart using the waffle package in R.
Here's the code:
waffle(table(dat$Age.Group),
rows=5,
title="Demographic Age Groups")
Then it shows this:
When I knitt it, it takes too much space, refer to the picture:
I'd like to put the text closer to the plot so it won't look awkward, and so I can fit more waffle charts in one page.
I really haven't tried anything, except changing the spacing between the squares, but that doesn't seem to be the problem. I've also looked up similar problems, but I can't find anything addressing to the removing of the margin.
Thank you so much in advance!
The issue is that waffle uses coord_equal under the hood. As a result the size of the plot is not adjusted to fill the size of the output device. If the size of the output device is larger than needed for the plot it is filled up with white space.
One option would be to set equal=FALSE in waffle. However, in that case you will no longer get squares but rectangles.
Second option would be to reduce the size or the height of the output device via chunk options, i.e. the size used by Rmarkdown or knitr to render your plot which by default is a 7 x 7 inches. To this end you could set fig.height or as an alternative set the aspect ratio using fig.asp:
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r, include=FALSE}
library(waffle)
```
```{r, include=FALSE}
parts <- c(One=80, Two=30, Three=20, Four=10)
chart <- waffle(parts, rows=8, equal = FALSE)
```
```{r fig.cap="Default"}
chart + ggplot2::labs(title = "Default")
```
```{r fig.asp=.4, fig.width = 7, fig.cap="Set the aspect ratio"}
chart + ggplot2::labs(title = "Set the aspect ratio")
```
```{r fig.height = 2.8, fig.width = 7, fig.cap="Reduce the figure height"}
chart + ggplot2::labs(title = "Reduce the figure height")
```

How to resize RMarkdown page to fit a big plot (non-rescaled igraph)

I need to fit a big igraph plot in an RMarkdown document, but a lot of the nodes and labels overlap (in a way similar to the image below).
I figured using the 'rescale=FALSE' argument could work, but then the problem is that the plot size is bigger than the page size, regardless of the fig.height, fig.width options.
Below you can see a reproducible example (save as .Rmd and Knit):
---
output: pdf_document
---
# How to resize page to fit plot?
```{r pressure, echo=FALSE, fig.height=20, fig.width=20, message=FALSE, warning=FALSE}
library(igraph)
st <- make_star(500)
set.seed(100)
plot(st, vertex.size=10, vertex.label=NA, rescale=FALSE)
```
There is a way to adjust the page size to a non-rescaled igraph?
You can adjust the page size by adding the classoption in the YAML.
But you can also play around with the fig size and the xlim() and ylim() to adjust the figure inside the page as answered here.
---
output:
pdf_document:
documentclass: article
classoption:
- a1paper
---
# How to resize page to fit plot?
```{r pressure, echo=FALSE, fig.height=30, fig.width=40, message=FALSE, warning=FALSE}
library(igraph)
st <- make_star(500)
set.seed(100)
plot(st, vertex.size=10, ylim=c(3,5), xlim = c(-7, 15),vertex.label=NA, rescale=FALSE)
```

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")
```

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.

knitr: How to show two plots of different sizes next to each other?

I wanted to generate two images of different sizes, but show them side-by-side. Is this possible?
This works, but then they have to be the same size:
```{r two_plots_same_size_side_by_side, fig.width=5, fig.height=5}
plot(...)
plot(...)
```
This doesn't work, but it could since in Markdown, lines that are separated by a single newline, appear on the same line.
```{r normal_plot, fig.width=5, fig.height=5}
plot(...)
```
```{r tall_plot, fig.width=5, fig.height=9}
plot(...)
```
Another option, if you're outputting to HTML is to use the out.extra= chunk option, and set them to be float objects within a block. For example.
```{r fig.width=4, fig.height=6,echo=FALSE,out.extra='style="float:left"'}
plot(cars)
```{r fig.width=8, fig.height=6,echo=FALSE, out.extra='style="float:left"'}
plot(cars)
```
One option would be to make a single wide graph with the R commands and give knitr just the one graph to deal with, maybe something like:
```{r fig.width=10, fig.height=9}
layout( cbind( c(0,0,1,1,1,1,1,0,0), rep(2,9) ) )
plot(...)
plot(...)
```
Yet another option is to use a vector for out.width or out.height, if you do not mind resizing the plots, e.g.
```{r out.width=c('500px', '300px'), fig.show='hold'}
boxplot(1:10)
plot(rnorm(10))
```
You can also use grid.arrange from gridExtra which works with grob or ggplot objects
require(gridExtra)
pre_fig <- rasterGrob(readPNG("paper_figures/surf_0000.png"), interpolate=TRUE)
post_fig <- rasterGrob(readPNG("paper_figures/surf_0044.png"), interpolate=TRUE)
grid.arrange(pre_fig, post_fig, ncol=2)

Resources