Code Learner
Code Learner

Reputation: 195

Overlapped grobs generated by arrangeGrob when view from RStudio and knit to PDF

I'm using RStudio under windows 10. I want to generate a PDF report. Below is a sample code showing the problem.

library(ggplot2)
library(grid)
library(gridExtra)
x <- data.frame(x=c(1:100), y=c(1:100))
x_t1 <- data.frame(a = 1, b = 1)
x_t2 <- data.frame(a = 2, b = 2)
x_t3 <- data.frame(a = 3, b = 3)
x_grobs <- list(
  textGrob("text 1"),
  textGrob("text 2"),
  tableGrob(x_t1),
  textGrob("text 4"),
  tableGrob(x_t2),
  textGrob("text 6"),
  tableGrob(x_t3),
  ggplotGrob(ggplot(x, aes(x, y))+geom_point())
)
x_heights <- c(rep(1, 7), 14)
x_arrgorb <- arrangeGrob(grobs=x_grobs,
                         ncol = 1,
                         heights = x_heights)
grid.newpage()
grid.draw(x_arrgorb)

The output view from my computer is like below: output of the code

You can see that though grobs are arranged in sequence and heights as expected, they are heavily overlapped. When I knit it to an A4 size PDF, the result is similar. All grobs squeezed on the top half of the page, leave most spaces empty: pdf output

I tried to set the viewport but did not end up with difference. I think it seems to be related to the plotting area, which has a fixed size, and all grobs are squeezed to fit in this plotting area. I don't know how to adjust this, or if this is the root cause. Please advise. Thank you.

Upvotes: 2

Views: 755

Answers (2)

Peter
Peter

Reputation: 7770

The issue appears to be with the definition of the x_heights. The first two grob are text and should have height 1 and then the first tableGrob is plotted with height 2. Edit the x_heights as

x_heights <- c(1, 1, 2, 1, 2, 1, 2, 14)

The resulting plot I get is:

enter image description here

Upvotes: 0

Marius
Marius

Reputation: 60060

To change the figure size so there is room for the plot when rendering to PDF, use the chunk options for your plotting code chunk and change fig.height and fig.width:

```{r chunkname, fig.height=10, fig.width=8}
<plotting_code>
```

Upvotes: 1

Related Questions