1

In r notebooks or markdown documents, if one specifies fig.width or fig.height for generating an image with ggplot, the size of the box containing the actual data is heavily influenced by the size of the margins and their elements (labels, legends etc.). So for example, if one rotates the x-axis-labels, the height of the box becomes smaller (see image), if one adds a legend, the width gets smaller.

My goal is to have the boxes containing the data in different figures the same size. How would one achieve that? The code for the two images can be found further down.

1

MWE for the sample images.

---
title: "R Notebook"
output:
  pdf_document: default
  html_notebook: default
---
library(ggplot2)
data(iris)
ggplot(iris, aes(Sepal.Length)) +
  geom_bar() +
  theme_linedraw()
library(ggplot2)
data(iris)
ggplot(iris, aes(Species, fill=Species)) +
  geom_bar(position = position_dodge2(preserve = "single")) +
  theme_linedraw() +
  theme(axis.text.x = element_text(angle=45, vjust=0.5))
Manuel
  • 111
  • 2
  • 1
    The {ggh4x} package has [`force_panelsizes()`](https://teunbrand.github.io/ggh4x/articles/Facets.html#panel-sizes-1) that lets you fix the size of the panel. You'd just need to make that the panel size and figure size are respectively small and large enough that there is space for plot decoration. (Disclaimer: I wrote ggh4x) – teunbrand Feb 26 '22 at 14:56
  • @teunbrand thanks, that helps (and thanks for writing ggh4x :))! Two questions though: 1) Does `force_panelsizes()`need a `facet_grid()` statement beforehand or does it work without? 2) I'm not quite sure, how the relative/absolute panel sizes work together with the `fig.width` and `fig.height`: For something like `force_panelsizes(cols=c(unit(4,"cm")), rows=(1), respect=TRUE)` *without* any `fig.width`, `fig.height`limitations, I would expect a panel of width 4 cm and equally high height. However, this does not seem to be the case. What am I doing wrong? – Manuel Feb 27 '22 at 09:49
  • 1
    1) No it works with `facet_null()` too, which, thinking about it, might be worth emphasising in the docs. 2) The rows should be `unit(4, "cm")` too if you want them to be equal. The `respect` argument only applies to `null` units in horizontal and vertical direction, i.e. setting `cols = unit(2, "null"), rows = unit(0.5, "null")` should give a panel 4x as wide as it is tall. `fig.width` and `fig.height` are ignored, you can easily make a plot smaller or larger than the device size (but when larger, the device won't show everything). – teunbrand Feb 27 '22 at 11:42
  • @teunbrand Thanks, appreciated. What additionally messed up the size of my figures was, that I used `cols = c(unit(4, "cm"))` instead of omitting the `c()` vector bit. With `cols = unit(4, "cm")`, it works perfect. Feel free to formulate your comment as answer. – Manuel Feb 27 '22 at 16:01

0 Answers0