R Notebook ignoring dynamic fig.height for chunk

I have a plot in an R Notebook whose height I want to vary depending on the number of data series being plotted. According to this StackOverflow I can define a variable in an earlier chunk with the desired height and then reference it as the value of fig.height for the chunk containing the plot. Something like this:

---
title: Sample
output: html_notebook
---
    
``` {r}
library("ggplot2")
    
targetCustomers <- data.frame(customer = c('cust1'), value = c(19)) 
chartHeight <- .3 * (nrow(targetCustomers) + 1)
```

```{r fig.width = 3.5, fig.height = chartHeight}
ggplot(targetCustomers) +
  geom_col(aes(x = customer, y = value), fill = "purple") +
  coord_flip()
```

When I actually do this and then run the chunks / preview the fig.height is ignored and just uses the default height.

If I use a constant for fig.height it sizes as expected

```{r fig.width = 3.5, fig.height = .6}
ggplot(targetCustomers) +
  geom_col(aes(x = customer, y = value), fill = "purple") +
  coord_flip()
```
1 Like

I cannot replicate your issue with an RMarkdown document. This seems to work for me when kniting to HTML and PDF.

Are you by chance having this issue when clicking to Preview the rmarkdown notework?
If you are, be sure to run the line in which chartHeight is assigned. Preview will look for that value in your environment when generating the notebook HTML.

Thank you for the response. It appears this is a preview only problem. I tried knitting to HTML and the graph is sized as expected. The inline output of the plot in the editor and the plot output if I just select Preview are not sized correctly though. (I hadn't ever been doing a final knit to HTML, just iterating and previewing and using the output from that)

Well, I can replicate the Previewing issue using RStudio Cloud (RStudio 1.2.451.1) at least. With these file contents:

---
title: "Sample"
output:
  html_notebook:
    df_print: paged
---
    
```{r}
library("ggplot2")
    
targetCustomers <- data.frame(customer = c('cust1'), value = c(19)) 
chartHeight <- 4
```

```{r, fig.height=4, fig.width=4}
ggplot(targetCustomers) +
  geom_col(aes(x = customer, y = value), fill = "purple") +
  coord_flip()
```

```{r, fig.height=chartHeight, fig.width=4}
ggplot(targetCustomers) +
  geom_col(aes(x = customer, y = value), fill = "purple") +
  coord_flip()
```

If I run all chunks, and then Preview, I get this:
http://rpubs.com/jcblum/399125
Note that the two plots should have identical sizes/aspect ratios, but they do not. The two plots have different size/aspect ratios in the inline preview, as well.

Knitting to HTML works fine, as previously noted (the two plots have the same size/aspect ratio).

(Edited because I initially copy-pasted the source after I'd tried knitting, so of course a new output line had been added to the YAML which was not there when I initially Previewed)