Search code examples
rr-markdownknitrflexdashboard

flexdashboard second plot is much smaller than first plot


When I plot several plots in an .Rmd file with flexdashboard, the second plot shows up much smaller than the first. Here is a screenshot from the reprex below.

Smaller second plot with flexdashboard

Why the second plot is much smaller than the first and how can I make them the same size?

I understand flexdashboard often resizes items to fit screen, but am lost on what exactly is happening here. I found the exact same question on SO from Oct 2021: R Flexdashboard multiple plots sizing, but is unanswered.

Here is a simple reprex.

---
title: "Reprex"
output:
  flexdashboard::flex_dashboard:
    orientation: rows
    vertical_layout: scroll
---

My Tab
=======================================================================

```{r include=TRUE, results="asis", echo=FALSE, fig.height=3, fig.width=5}
library(dplyr)
library(ggplot2)
dat <- tribble(
  ~item, ~subitem, ~x, ~y,
  'foo', 'a', 3.2, 101,
  'foo', 'a', 2.2, 94,
  'foo', 'a', 1.2, 32,
  'foo', 'b', 12.2, 49,
  'foo', 'b', 0.2, 83,
  'foo', 'b', 7.7, 29,
  'bar', 'a', 13.2, 10,
  'bar', 'a', 7.0, 8,
  'bar', 'a', 0.1, 100,
  'bar', 'b', 10.2, 93,
  'bar', 'b', 4.0, 74,
  'bar', 'b', 10.3, 35
)

items <- unique(dat$item)
for(i in items){
  cat("\n")
  cat(paste("####", i, "\n"))
  cat("\n")
  
  p <- ggplot(filter(dat, item == i), aes(x, y)) +
    geom_point() +
    facet_wrap(~subitem)
  print(p)

  cat("\n")
}
cat("\n")
```

Solution

  • As per the flexdashboard docs,

    Dashboards are divided into columns and rows, with output components delineated using level 3 markdown headers (###).

    So as long as we stick to using three hash sign (i.e. ###), flexdashboard behaves consistently,


    ---
    title: "Reprex"
    output:
      flexdashboard::flex_dashboard:
        orientation: rows
        vertical_layout: scroll
    ---
    
    
    ```{r include=FALSE}
    knitr::opts_chunk$set(fig.height = 3, fig.width = 5)
    ```
    
    
    My Tab
    =======================================================================
    
    ```{r include=TRUE, results="asis", echo=FALSE}
    library(dplyr)
    library(ggplot2)
    dat <- tribble(
      ~item, ~subitem, ~x, ~y,
      'foo', 'a', 3.2, 101,
      'foo', 'a', 2.2, 94,
      'foo', 'a', 1.2, 32,
      'foo', 'b', 12.2, 49,
      'foo', 'b', 0.2, 83,
      'foo', 'b', 7.7, 29,
      'bar', 'a', 13.2, 10,
      'bar', 'a', 7.0, 8,
      'bar', 'a', 0.1, 100,
      'bar', 'b', 10.2, 93,
      'bar', 'b', 4.0, 74,
      'bar', 'b', 10.3, 35
    )
    
    items <- unique(dat$item)
    for(i in items){
      cat("\n")
      cat(paste("###", i, "\n"))
      cat("\n")
      
      p <- ggplot(filter(dat, item == i), aes(x, y)) +
        geom_point() +
        facet_wrap(~subitem)
      print(p)
    
      cat("\n")
    }
    cat("\n")
    ```
    

    flexdashboard with consistent sized plots