Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly set panel size (not just plot size) in ggplot2

Tags:

r

ggplot2

Is it possible to explicitly set the panel size (i.e., the gray grid panel) in a ggplot? I imagine (but can't find) that there is some ggplot extension that allows for arguments that resemble panel.width = unit(3, "in"), panel.height = unit(4, "in").

I have seen solutions for setting the size of the entire plot, or of getting multiple plots to align using the egg package. But nothing that would let me explicitly set the size of the panel.

library(dplyr)
library(ggplot2)
library(tibble)

ds_mt <- mtcars %>% rownames_to_column("model")
mt_short <- ds_mt %>% arrange(nchar(model)) %>% slice(1:4)
mt_long <- ds_mt %>% arrange(-nchar(model)) %>% slice(1:4)

p_short <- 
    mt_short %>% 
    ggplot(aes(x = model, y = mpg)) + 
    geom_col() + 
    coord_flip()

p_short

enter image description here

like image 654
Joe Avatar asked Nov 13 '18 16:11

Joe


People also ask

How to change size in ggplot?

How can I change the default font size in ggplot2? Set base_size in the theme you're using, which is theme_gray() by default. The base font size is 11 pts by default. You can change it with the base_size argument in the theme you're using.

What does %>% mean in Ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Introducing magrittr. Adding things to a ggplot changes the object that gets created.

How do I increase the width of a ggplot2?

To increase the width of axes (both X-axis and Y-axis at the same time) using ggplot2 in R, we can use theme function with axis. line argument where we can set element_line argument to a larger value.


1 Answers

The ggh4x package has a similar function to the egg solution presented in the other answer. A slight convenience is that the plot is still a valid ggplot after using the function, so it would work with ggsave() and other layers can be added afterwards. (disclaimer: I wrote ggh4x)

library(dplyr)
library(ggplot2)
library(tibble)
library(ggh4x)

ds_mt <- mtcars %>% rownames_to_column("model")
mt_short <- ds_mt %>% arrange(nchar(model)) %>% slice(1:4)
mt_long <- ds_mt %>% arrange(-nchar(model)) %>% slice(1:4)

mt_short %>% 
  ggplot(aes(x = model, y = mpg)) + 
  geom_col() + 
  coord_flip() +
  force_panelsizes(rows = unit(4, "in"),
                   cols = unit(3, "in"))

Created on 2021-04-21 by the reprex package (v1.0.0)

like image 67
teunbrand Avatar answered Sep 19 '22 23:09

teunbrand