Specify height and width of ggplot graph in Rmarkdown knitr output
62,467
Solution 1
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()
```
Solution 2
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"))
Solution 3
If you would like to do this for all plots then you can use the r setup
Rmd chunk at the beginning of the file.
knitr::opts_chunk$set(echo = TRUE, fig.width = 10, fig.height = 5)
Author by
user6571411
Updated on December 04, 2021Comments
-
user6571411 over 2 years
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?
-
skdhfgeq2134 about 5 yearsWould you like to elaborate on your answer for people who don't know what code chunk means?
-
daszlosek almost 5 yearsA code chunk is a part of the R markdown/ R Notebook formatting. This defines the space where you can write and execute your code. It is defined as ```{r} your code here ``` . More info can be found:rmarkdown.rstudio.com/lesson-3.html
-
jzadra about 4 yearsWhat if you want different sizes within a code chunk?
-
Chris Keefe over 3 years@jzadra, I'm not sure how to do that, or if it's even possible, but creating a separate chunk for each ggplot is trivial. Just close one chunk after your first plot (with triple backticks), then open another one with the new plot specifications (triple backticks followed by a description like that in curly braces above.
-
M4RT1NK4 over 2 yearsWhen I try this the plot sizes change only in the knitted document, but not in the output of the rmd editor. It changes only if I put
{r, fig.width=10,fig.height=11}
in every individual chunk. Is there a global way to set the size in the output of the editor?