How do I increase the grey plot area of a chart with one factor based axis and one numerical axis so that text labels in geom_text()
plots are in view and do not extend outside the plot area?
In particular, I would like to extend the grey area to provide a margin area within the plot area that allows the text labels to appear in full.
Or is there a better way?
You can change the layout option of each ggplot using ggplot_gtable
, then display all plots using grid.arrange
.
library(ggplot2)
library(gridExtra)
## create a dummy ggplot
(g1 <- ggplot(mtcars, aes(wt, mpg)) +
geom_text(aes(label=rownames(mtcars)), size=6, angle=45) +
theme(plot.margin = unit(rep(1, 4), "cm")))
Obviously the text labels do not extend outside the plot area. But the following code allows just that:
gg_table <- ggplot_gtable(ggplot_build(g1))
gg_table$layout$clip[gg_table$layout$name=="panel"] <- "off"
grid.draw(gg_table)
Create a gg_table for each panel, then use grid.arrange
to display all:
grid.arrange(gg_table, gg_table, gg_table, gg_table, ncol=2)
I know this is labor intensive, but you can write a function to create multiple ggplots and gg_tables to save time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With