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?
Specify height and width of ggplot graph in Rmarkdown knitr output
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()
```
Would you like to elaborate on your answer for people who don't know what code chunk means? –
Contaminate
A 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 –
Sapro
What if you want different sizes within a code chunk? –
Viscoid
@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. –
Didymium
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)
When 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? –
Vituperate 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"))
Currently in Quarto you can add the parameters as tags to a code block:
```{r}
#| fig-width: 10
#| fig-height: 5
ggplot(df, aes(x = x, y = y)) + geom_point()
```
© 2022 - 2024 — McMap. All rights reserved.