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()
```
Related
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'm creating a document with PDF output in R Markdown.
My code creates a number of tables and figures in a "for" loop, within the same code chunk. All the tricks I've seen to create a line break in a PDF document - with all sorts of combinations and permutations of preceding slashes and spaces (e.g., newline, linebreak, ,  , etc) are not working. So, I decided to cut some corners and just increase the plot space in my ggplot2 margins to create the illusion of more white space between my table and my graph.
Ideally, I'd love to know how to actually insert white space ( a line, or several lines) properly within a single code chunk, without getting an error.
However, I'd also settle for figuring out why the following code "works" to produce extra space in my ggplot2 plot when I have some background color (first plot) but doesn't work when the background color is white!!? This is truly bizarre behavior folks!
See my screenshot below and the code, with two identical code chunks - except the background color of the plot - where one plot with a light beige background shows the desired "white space" between the table and the plot title, and the plot following (white background) does not show the same "white space".
---
title: "I need a line break"
output: pdf_document
---
```{r setup, include=FALSE}
library(ggplot2)
library(knitr)
library(ggplot2)
knitr::opts_chunk$set(echo = FALSE,
include = TRUE,
message = FALSE,
warning = FALSE,
error = FALSE)
```
```{r, results = "asis", fig.height = 2}
for (i in 1) {
mytable <- kable((iris[c(1,2),]), booktabs = TRUE)
print(mytable)
myplot <- ggplot(iris) +
labs(title = "Gorgeous plot") +
geom_point(aes(Sepal.Length, Sepal.Width)) +
theme_void() +
theme(plot.background = element_rect(fill = "#FFFEEB", color = "white"),
plot.margin = unit(c(1, 0, 0, 0), "cm"))
print(myplot)
}
```
```{r, results = "asis", fig.height = 2}
for (i in 1) {
mytable <- kable((iris[c(1,2),]), booktabs = TRUE)
print(mytable)
myplot <- ggplot(iris) +
labs(title = "Gorgeous plot") +
geom_point(aes(Sepal.Length, Sepal.Width)) +
theme_void() +
theme(plot.background = element_rect(fill = "white", color = "white"),
plot.margin = unit(c(1, 0, 0, 0), "cm"))
print(myplot)
}
```
Can you add linebreaks with cat to solve your problem? E.g.
---
title: "I need a line break"
output: pdf_document
---
```{r setup, include=FALSE}
library(ggplot2)
library(knitr)
library(ggplot2)
knitr::opts_chunk$set(echo = FALSE,
include = TRUE,
message = FALSE,
warning = FALSE,
error = FALSE)
```
```{r, results = "asis", fig.height = 2}
for (i in 1:2) {
mytable <- kable((iris[c(1,i),]), booktabs = TRUE)
print(mytable)
cat("\\ ")
cat("\\linebreak")
cat("\\linebreak")
cat("\\linebreak")
myplot <- ggplot(iris) +
labs(title = "Gorgeous plot") +
geom_point(aes(Sepal.Length, Sepal.Width)) +
theme_void()
print(myplot)
cat("\\linebreak")
cat("\\linebreak")
}
```
(The cat("\\ ") is needed so that there is a line to end)
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
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.
Is there a way in RMarkdown to force R code and the figure that it produces to appear on the same page please? I am using Knit pdf. For example,
```{r}
ggplot(df, aes(x = x, y = y, col = sex_f)) + geom_point() +
ggtitle("Data from Children") +
labs(x = "Age (months)", y = "Height (cms)", col = "Child Gender") +
geom_smooth(method = "lm", se = FALSE) +
facet_grid(sex_f ~ town_f)
```
(which is not reproducible) produces code on one page and a plot on the next page. I have tried setting the figure width and height globally, for example
```{r global_options, include=FALSE}
knitr::opts_chunk$set(fig.width = 4, fig.height = 3,
fig.path = 'Intro_Figs/',
fig.show = 'asis',
fig.align = 'center',
warning = FALSE, message = FALSE)
```
with very small values, but this does not prevent all bad page breaks. Thank you.