0

In the following RMarkdown, I would like to have each barplot print so that the text size and box width are the same in each plot, and the height adjusts accordingly.

What is happening is that in the plots with few bars the bars are extremely wide, and in the plots with many bars the bars are thin and the labels squished.

---
title: "chunk plot height"
number_sections: yes
output: html_notebook
---

# Load Libraries
\```{r}
library(tidyverse)
library(magrittr)
library(rmarkdown)
\```


# Set Knitr Options
\```{r}
knitr::opts_chunk$set(
  echo=TRUE,
  dpi=300,
  fig.width=12
)
\```

# Plot
\```{r}
for (n in seq(10,50,10))
{
  knitr::opts_chunk$set(out.height=n)

  data = data.frame(
    X=sapply(c(letters, LETTERS)[1:n], function(x) rep(x,3) %>% paste0(collapse=''), USE.NAMES = F),
    Y=rnorm(n)
  )

  plt = 
    data %>%
    ggplot(aes(x=X, y=Y)) +
    geom_col(position=position_dodge(width=1, preserve='single')) + 
    coord_flip()

  print(plt)
}
\```

enter image description here

enter image description here

abalter
  • 9,663
  • 17
  • 90
  • 145
  • 1
    Possibly helpful idea here even though it's a different issue: https://stackoverflow.com/questions/16255579/how-can-i-make-consistent-width-plots-in-ggplot-with-legends, or here: https://stackoverflow.com/questions/18429244/constant-width-in-ggplot-barplots – MrFlick Jan 13 '20 at 21:56
  • Those look useful. But pretty complex. In my old Matlab days, I could specify bar width and plot aspect ratio declaratively. – abalter Jan 13 '20 at 22:10
  • Yeah, R doesn’t work that way sadly. I’d designed to scale to any graphics device size. A ggplot doesn’t have much control over its own size in R. But in most cases this is a very useful behavior. – MrFlick Jan 13 '20 at 22:12
  • `fig.height='auto'` would be great. – abalter Jan 13 '20 at 22:23

0 Answers0