55

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?

4 Answers 4

118

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()
```
Sign up to request clarification or add additional context in comments.

4 Comments

Would you like to elaborate on your answer for people who don't know what code chunk means?
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
What if you want different sizes within a code chunk?
@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.
16

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)

1 Comment

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?
12

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"))

Comments

4

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()
```

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.