Search code examples
rggplot2gtable

Extract panel size from ggplot object


I try to extract width and height of the panel from the ggplot object. What I have done so far:

library(ggplot2)
library(gtable)
# Create object
p <- ggplot(iris, aes(x = Sepal.Length)) +
  geom_histogram()
# Convert the plot to a grob
gt <- ggplotGrob(p)
# Extract panel
panel <- gtable_filter(gt, "panel")

Now I'm stacked with extracting the correct size. Any idea how to proceed?


Solution

  • panel$widths will return 1null. That's a feature of ggplot2: the panel is sized such that it will expand to fill the available space on the viewport.