Reputation: 431
I am creating a gtable consisting of 3 x ggplot grobs using cbind, but I would like to make the middle column less wide than the 1st and 3rd column. How would I go about doing this?
The centre column only contains text so does not need equal width to the other columns containing charts:
library(grid)
# get ggplot grob
p4grob <- ggplotGrob(p4)
gdp4grob <- ggplotGrob(gdp4)
labels4grob <- ggplotGrob(labels4)
gt = cbind(gdp4grob, labels4grob, p4grob)
grid.newpage()
grid.draw(gt)
Many thanks!
Upvotes: 0
Views: 407
Reputation: 431
Good suggestion in comments to use gridExtra
. Much easier. But, as mentioned, I still had to do a couple of simple hacks to ensure the 3 x ggplots aligned properly, because grid.arrange
bottom-aligns the content of a column (a bit odd and I didn't overcome this).
My resulting grid.arrange
code is as-follows, and totally moves away from using extracted grobs and cbind and leaves it to gridExtra::grid.arrange()
```{r, fig.show='hide'}
library(grid)
# Prepare custom pyramid plot
g <- gridExtra::grid.arrange(NULL,
gdp4,
labels4,
p4,
NULL,
widths = c(0.1,2,0.65,2,0.1),
nrow = 1,
top = textGrob(
'Top 10 Waste Generating Coastal Nations By Region\nPlastic Waste vs GDP Per Capita',
gp=gpar(col="white"),
),
padding = unit(1, "cm")
)
Note that I actually created 5 columns, with the left-most and right-most columns being NULL
, just because the output was cropping the numbers in the x-axis, and that was how I added a small amount of padding to the chart.
Also, obviously a few additional features used working towards the final product (e.g. don't confuse padding
with padding the overall chart/grid/table because it is just padding the title).
I also ended up using cowplot
to adjust the theme of the resulting variable from grid.arrange
, explaining the change in appearance to blue background (and a few other alterations were done in ggplot2
prior to final product, so the change in appearance is not resulting from using grid.arrange()
).
```{r fig.align="center", fig.height = 10, fig.width = 10}
# Format and output chart
g2 <- cowplot::ggdraw(g) +
theme(plot.background = element_rect(fill = "#172f52"),
)
plot(g2)
Also note that I added fig.hide
for the original R Markdown chunk because I couldn't stop grid.arrange()
from outputting the chart, even when I was assigning it to a variable, so had to hide it via R Markdown tags, and then put the cowplot
plot in a separate chunk for output.
Upvotes: 0