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.
Related
In r notebooks or markdown documents, if one specifies fig.width or fig.height for generating an image with ggplot, the size of the box containing the actual data is heavily influenced by the size of the margins and their elements (labels, legends etc.). So for example, if one rotates the x-axis-labels, the height of the box becomes smaller (see image), if one adds a legend, the width gets smaller.
My goal is to have the boxes containing the data in different figures the same size. How would one achieve that? The code for the two images can be found further down.
MWE for the sample images.
---
title: "R Notebook"
output:
pdf_document: default
html_notebook: default
---
library(ggplot2)
data(iris)
ggplot(iris, aes(Sepal.Length)) +
geom_bar() +
theme_linedraw()
library(ggplot2)
data(iris)
ggplot(iris, aes(Species, fill=Species)) +
geom_bar(position = position_dodge2(preserve = "single")) +
theme_linedraw() +
theme(axis.text.x = element_text(angle=45, vjust=0.5))
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'}
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.
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))
```
When using RMarkdown + Knitr to make an HTML output of my code/plots, the plot images always appear as expected in RStudio with the correct width/height sizes specified in the chunk options, but if I then use Knitr to put everything together in an HTML document, the plots are all resized to a smaller default it seems.
Viewing each plot separately in a new tab shows their large size as desired but why can't this be the way they are shown in the HTML. Any setting I can change for this?
There is a difference between fig.width and out.width, and likewise between fig.height and out.height. The fig.* control the size of the graphic that is saved, and the out.* control how the image is scaled in the output.
For example, the following .Rmd file will produce the same graphic twice but displayed with different width and height.
---
title: "Example graphic"
---
```{r echo = FALSE, fig.width = 14, fig.height = 9, out.width = "588", out.height = "378"}
library(ggplot2)
ggplot(mpg, aes(x = year, y = cyl)) + geom_point()
```
```{r echo = FALSE, fig.width = 14, fig.height = 9, out.width = "1026", out.height = "528"}
library(ggplot2)
ggplot(mpg, aes(x = year, y = cyl)) + geom_point()
```