Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing plot print aspect ratio or size in an R notebook in RStudio without the plot becoming full width

I would like to change the aspect ratio or figure size of a plot that gets printed within an R notebook in RStudio.

I'm able to adjust the aspect ratio with the fig.asp chunk argument. For example, in the minimal example below, the plot aspect ratio correctly becomes 2. However, at the same time, the plot also becomes very large, full width within the notebook (screenshot below). How can I change the aspect ratio without the plot becoming full width within my notebook? Specifying fig.width or out.width arguments doesn't make a difference.

Environment:

R version: 3.6.1 (2019-07-05)
RStudio version: 1.2.1541
platform       x86_64-apple-darwin15.6.0   
arch           x86_64                      
os             darwin15.6.0                
system         x86_64, darwin15.6.0 

Minimal example:

---
title: "R Notebook"
output: html_notebook
---

This is an [R Markdown](http://rmarkdown.rstudio.com) Notebook. When you 
execute code within the notebook, the results appear beneath the code. 

Try executing this chunk by clicking the *Run* button within the chunk or 
by placing your cursor inside it and pressing *Cmd+Shift+Enter*. 

```{r, fig.asp=2, fig.width='200px'}
plot(cars)
```

Problem:

enter image description here

like image 773
Harry M Avatar asked Oct 22 '25 10:10

Harry M


1 Answers

In RMarkdown, you don't need to surround the code-chunk options in quotation marks.

For your example, by simply removing the ' from your code-chunk options line (like this: out.width=200px) allows the plot to be displayed as expected.

This code:

```{r, fig.asp=2, out.width=200px}
plot(cars)
```

Has this result:

Screen Shot with <code>out.width=200px</code>

Alternatively, you could also try specifying the fixed width and height of the figures, using the fig.width and fig.height options. These also do not need quotation marks (').

For example, these two code chunks have very different aspect ratios:

```{r, fig.width=12, fig.height=4}
plot(cars)
```

and

```{r, fig.width=4, fig.height=12}
plot(cars)
```

Have results like this:

Screen shot of two plots specifying <code>fig.width</code> and <code>fig.height</code>

I trust that helps.

like image 78
chrimaho Avatar answered Oct 25 '25 01:10

chrimaho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!