Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify height and width of ggplot graph in Rmarkdown knitr output

Tags:

r

ggplot2

knitr

I have created a plot with ggplot2 where the x-axis labels are not readable unless the plot is larger than default. When viewing in Rstudio I am able to resize dynamically. When saving with ggsave() I am able to specify height and width. How would I do this within the Rmarkdown file so that the output contains a plot of the desired size?

like image 700
user6571411 Avatar asked Sep 22 '16 08:09

user6571411


People also ask

How do I change the size of a plot in Rmarkdown?

For a plot of different size, change simple the numbers: {r fig2, fig. height = 3, fig. width = 3, fig. align = "center"} .

Can you use Ggplot in R markdown?

R markdown cannot include ggplot figures.

How do I show plots in R markdown?

In RStudio, when you open a new RMarkdown file, in the editor pane, there is a cogwheel button / menu where you can choose "Chunk Output Inline". That should put the plots into the document.

How do you save a plot in Rmarkdown?

You want to make sure that you save images you create in your rmarkdown document. To do this automatically, and avoid writing things like ggsave(plot) or dev. off() , just create the plots in rmarkdown, and tell it you want to save the output. In the funky looking code at the top, the YAML, specify keep_md: yes .


2 Answers

You can specify height and width in the code chunks

```{r, fig.width=10,fig.height=11}
df %>% ggplot(aes(x = x, y = y)) + geom_point()
```
like image 145
user6571411 Avatar answered Oct 10 '22 00:10

user6571411


As a side-answer, note that you can also use metric-system units using ggplot2::unit():

library(ggplot2)
knitr::opts_chunk$set(fig.width=unit(18,"cm"), fig.height=unit(11,"cm"))
like image 8
Dan Chaltiel Avatar answered Oct 10 '22 00:10

Dan Chaltiel