Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increasing the plot area in ggplot to cope with geom_text at plot edges

Tags:

plot

r

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?

ggplot showing geom_text() plot where labels 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?

like image 347
psychemedia Avatar asked Sep 17 '12 20:09

psychemedia


1 Answers

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)

enter image description here

I know this is labor intensive, but you can write a function to create multiple ggplots and gg_tables to save time.

like image 93
Masato Nakazawa Avatar answered Nov 16 '22 00:11

Masato Nakazawa