I am writing a report in R markdown with a pdf output. I have several plots and I would like to display four plots per page laid out in a 2x2 matrix. Is there a way to get them to display like that with separate captions?
Here is what I have tried so far:
Package gridExtra - I can easily setup the layout I want but I wasn't able to add captions to the plots.Is there an option to add captions to the plot in
grid.arrange
?Placing each plot in a different chunk and playing with R chunk options. Basically setting
out.width='.49\\linewidth', fig.align='right'
andfig.align='left'
alternatively. Here I can set individual captions withfig.cap
but the plots always show up on separate pages.I tried playing with the
fig.width
andfig.height
options and was able to get them to display on the same page on their respective left or right sides of the page. However the caption always takes the full page width and stays in center instead of wrapping with the plot size. Is there a way to make caption follow the plot sizing rules?
Here is a sample code:
```{r, echo=FALSE, cache=FALSE, results=FALSE, warning=FALSE, comment=FALSE, message= FALSE, eval =T, fig.height= 9}
p1<- ggplot(mpg, aes(displ, hwy, colour = class)) +
geom_point()+
labs(caption = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ")+
theme(plot.caption = element_text(hjust = 0.5))
p2<- ggplot(mpg, aes(displ, hwy, colour = class)) +
geom_point()+
labs(caption = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ")+
theme(plot.caption = element_text(hjust = 0.5))
p3<- ggplot(mpg, aes(displ, hwy, colour = class)) +
geom_point()+
labs(caption = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ")+
theme(plot.caption = element_text(hjust = 0.5))
p4<- ggplot(mpg, aes(displ, hwy, colour = class)) +
geom_point()+
labs(caption = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ")+
theme(plot.caption = element_text(hjust = 0.5))
library(gridExtra)
grid.arrange(p1,p2,p3,p4)
```