RMarkdown and ggplot: Axis labels cut off - r

In an RMarkdown PDF document, I am generating a heatmap with rather long tick labels. For some reason, this causes the y-axis label and the colour legend to be cut off. I already attempted several tricks in order to fix this, but so far to no avail. Here is my reprex:
---
title: "Test"
output: pdf_document
draft: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = FALSE, fig_crop=FALSE
)
```
```{r dependencies, include=FALSE}
library(tidyverse)
options(print_format="tex")
```
```{r, include=FALSE}
# Dummy data
set.seed(1234)
Count = rep((1:5), 8)
Gadget = rep(c("BANANA", "APPLE", "PEAR", "ORANGE", "ENCYCLOPEDIA", "XYLOPHONE", "TOMATO", "POTATO"), each=5)
GadgetScore = runif(40, 0, 100)
data = data.frame(Count, Gadget, GadgetScore)
```
```{r}
# Generate heatmap
maxi = max(data$GadgetScore, na.rm=TRUE)
mini = min(data$GadgetScore, na.rm=TRUE)
midi = mini+(maxi-mini)/2
ggplot(data, aes(Count, Gadget, fill=GadgetScore)) + geom_tile() +
scale_fill_gradient2(name="Gadget score value", low="red", mid="yellow", high="green", midpoint=midi) +
labs(x="Count", y="Gadgets")
```
Here is the output:
As you can see, the y-axis label Gadgets on the left hand side, and the colour legend label Gadget score value on the right hand side are cropped. As I said, I already tried a couple of hints from StackOverflow, but so far, none of them worked.
Trick 1: Following this post, I tried adding
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
to the ggplot elements.
Trick 2: Following this post, I tried to adapt the width of the plot chunk with something like
fig.width = 5
Trick 3: Following this post, I tried adding
theme(plot.margin = margin(100, 100, 100, 100))
to the ggplot elements.
Trick 4: I tried adding the option crop = FALSE and fig_crop=FALSE to the setup chunk.
Unfortunately, none of these tricks worked. Any help will be much appreciated.

In my case, the cropping error was related to a deprecated version of GhostScript. After updating GhostScript to the latest version (9.54.0), I can run the reprex without any image cropping issues.

The code works perfectly for me. However, you can check the alignment of the image, maybe if you place it a bit more to the right you can see the label. For this try in the last chunk to add {r, fig.dim = c(5, 2.5), fig.align = 'right'}

Related

A ggmap too small when rendered within a Rmd file?

I generate a ggmap plot that when executed from the r script looks perfect; however, the same plot in a Rmd file looks too small with half the width and disproportionate w.r.t the points being plotted.
What setting would help making the ggmap plot to take as much space as possible? My plotting code looks like this:
library(tidyverse)
library(ggmap)
library(ggplot2)
ggmap(map) +
scale_colour_manual(values = colorSpec) +
geom_point(data=df, aes(x=lon, y=lat, colour=Technology, size=score),
position = position_jitterdodge(jitter.width=0.01, jitter.height=0.01, seed=1)) +
theme(legend.position="bottom", plot.title = element_text(hjust = 0.5),
legend.text=element_text(size=6), legend.title = element_blank())
This is the correct expected output when plotted from the r script:
And this is the smaller and disproportionate output when plotted from the rmd and generated PDF file:
The issue comes not from ggplot, but from the markdown settings (e.g. figure margins).
You can try by specifying the plotting area when calling the ggplot block in the markdown.
# using knitr::spin()
#+ out.width = "100%", fig.align = "center", echo=FALSE
# using Rmarkdwon
```{r, out.width = "100%", fig.align = "center", echo=FALSE}
your ggplot code
```
# or
```{r, fig.width=10, fig.height=2, fig.fullwidth=TRUE}
your ggplot code
```
You can also try to increase the overall width of the page with options(width="a high value here")
Note that if you are using a template, all the above options will fail as you need to modify the template css file. If you cannot do that, then you may want to consider saving the ggplot as image and import it in your document.
For the people wondering about knitr::spin(), I suggest to spend some time reading about it (here or here.

How can I scale the label size of ggplot2 plots in rmarkdown

Hello I am generating report with rmarkdown
I decided to use ggplot2 graphs as it seems that knitr rmarkdown ggplot2 works better together.
I'd like to globally increase the axis labels, tick label, title of my ggplot2 plots in the html_notebook document rmarkdown::render'ed.
Can I do this in the yaml or by setting something in a global chunk option ?
You could use theme_update() in the setup chunk of your rmarkdown document to modify the active theme, overwriting the defaults for all subsequent plots. For example:
```{r setup, include=FALSE}
library(ggplot2)
theme_update(# axis labels
axis.title = element_text(size = 30),
# tick labels
axis.text = element_text(size = 20),
# title
title = element_text(size = 50))
```

Scaling plotly figures in knitr Latex document

I'm trying to include a plotly chart into a Latex document with knitr. Since knitr includes the webshot package this works well. But if I want to resize my figure for the latex output, the figure environment gets bigger but the plotly chart is not scalled to the manually set figure width and height.
Specifing the webshot options like recommend here, did not work neither. Scaling a ggplot chart works well, but how can I get the same results for the plotly chart?
\documentclass{article}
\usepackage{cleveref}
<<setup, echo=FALSE, message = FALSE, warning = FALSE>>=
library(ggplot2)
library(plotly)
#
%Preamble
\title{GGplot vs. Plotly }
\author{authors}
\date{2016}
\begin{document}
\maketitle
\section{Comparison ggplot with plotly}
This document illustrate the difference between ggplot and plotly. The chart in (\Cref{fig:ggplot}) is well placed in the document, but the chart in (\Cref{fig:plotly}) is neither scalled to the figure width, nor positioned next to the label.
<<ggplot, fig.lp="fig:", fig.cap = 'This is rendered with ggplot()', echo=FALSE, fig.width = 10, fig.height = 6>>=
ggplot(midwest, aes(x = state, y = percollege, colour = state)) + geom_boxplot()
#
<<plotly, fig.lp="fig:", fig.cap = 'This is rendered with plotly()', echo=FALSE, fig.width = 10, fig.height = 6, screenshot.opts = list(delay = 2, cliprect = 'viewport')>>=
plot_ly(midwest, x = ~state, y = ~percollege, color = ~state, type = "box")
#
\end{document}
I saw that the graphic file figure/plotly-1.pdf (generated by knitr/webshot, and then loaded into latex) has two pages and the plotly object is somewhere in the upper left corner. I guess the margins included in the webshot figure are in fact the problem.
R 3.2.3
knitr 1.14
ggplot2 2.1.0
plotly 4.5.2

R markdown linking to a figure

I am creating a report with multiple figures and tables. I'd like to refer to them in the accompanying text. I've tried the following:
---
title: "Test"
output:
pdf_document
---
Figure \ref{test} is a graph
```{r test, fig.cap="This is a graph"}
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30))
ggplot(df, aes(x = gp, y = y)) +
geom_point()
```
This is text to follow the diagram
\pagebreak
This is another page but can still link to Figure \ref{test}
But the result is:
Figure ?? is a graph
...
This is another page but can still link to Figure ??
Is there a default way to do this in R markdown without having to write functions myself
I think I found an answer here- https://github.com/yihui/knitr/issues/323
Using this code seemed to provide the behavior I think you're looking for, if I'm understanding correctly.
---
title: "Test"
output:
pdf_document
---
Figure \ref{fig:plot} is a graph
```{r plot-ref, fig.cap = "This is a graph\\label{fig:plot}"}
library('ggplot2')
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30))
ggplot(df, aes(x = gp, y = y)) +
geom_point()
```
This is text to follow the diagram
\pagebreak
This is another page but can still link to Figure \ref{fig:plot}

Knitr: figure legend too big

When I knit a Tufte handout pdf the legends of some figures are often too large. I'm knitting a fig.fullwidth=TRUE section and have varied the fig.width= argument from 2 to 50 to see if they make any difference. When I specify fig.width=2 I end up with a small figure and the legend expands hugely to fill the space:
Obviously the next step was to try a larger fig.width but these stopped making any difference after about fig.width=10 (which is still better though):
I assume the fig.width is the width in inches, so this makes sense as the paper size I'm using is A4 so about 8 inches.
My question is, how do I reduce the size of the legend further so it takes up a more appropriate size? I've tried manually setting the font sizes with:
theme(legend.title = element_text(size = 9),
legend.text = element_text(size = 8))
but these have had no affect to the knitr legend (although they do affect the plot when manually plotted as expected).
Minimal reproducible example (paste into a .Rmd file and knit):
---
title: "knitr: figure legend too big"
documentclass: article
classoption: a4paper
output: rmarkdown::tufte_handout
---
```{r setup, include=FALSE}
require("knitr")
require("rgdal")
require("rgeos")
require("maptools")
require("ggplot2")
```
```{r, fig.cap="test", fig.fullwidth=TRUE, fig.width=10}
# About 650k
download.file("https://census.edina.ac.uk/ukborders/easy_download/prebuilt/shape/England_gor_2011_gen.zip",
destfile = "regions.zip")
unzip("regions.zip")
regions <- readOGR(dsn = ".", "england_gor_2011_gen")
regions#data$test <- as.character(1:nrow(regions#data))
regions_f <- fortify(regions, region = "name")
regions_f <- merge(regions_f, regions#data, by.x = "id", by.y = "name")
ggplot() +
geom_polygon(data = regions_f, aes(long, lat, group = group, fill = test),
colour = "black") +
coord_equal() +
theme(legend.title = element_text(size = 9), # doesn't seem to make
legend.text = element_text(size = 8)) # a difference to knitr
```
As always, thanks for looking at this.
I think that is due to the fact that maps have to set the aspect ratio to 1. The default figure height in tufte::tufte_handout() is 2.5, so even if the figure width is as large as 10, the actual map size is still like 2.5 x 2.5. When you increase fig.width, you also need to increase fig.height, e.g.
```{r, fig.cap="test", fig.fullwidth=TRUE, fig.width=6, fig.height=6}
Actually, when you only set fig.width=10, knitr did generate a 10 x 2.5 PDF image, but rmarkdown has enabled the figure cropping feature by default, so the large white margins on the left and right of the figure are cropped, and you ended up with a 2.5 x 2.5 figure.

Resources