Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 facet margin

Tags:

r

ggplot2

I use facet_wrap to plot some data. Here is an example:

library (ggplot2)
library (reshape)

# generate some dummy data
x = seq(0,1,0.05)
precision = sqrt(x)
recall    = 1 - precision
fmeasure  = 2 * (precision * recall) / (precision + recall)

# prepare it for plotting
df = data.frame(x=x, precision=precision, recall=recall, fmeasure=fmeasure)
df = melt(df, id.vars=c(x))

# plot it
p = ggplot(df, aes(x=x, y=value, group=variable))
p = p + geom_line() + facet_wrap(~variable, ncol=3)
p = p + coord_cartesian(xlim=c(0,1), ylim=c(0,1)) # second plot is without this line
print (p)

Figure 1: Plot for above code. Plot with xlim and ylim

However, what you see in Figure 1 is that the first and last labels of consequent facets overlap. This could be fixed by increasing the space between facets. Other option is to remove xlim and ylim ranges as depicted in Figure 2, but this keeps unnecessary space in the facet itself.

Figure 2: Plot with line p = p + coord_cartesian(xlim=c(0,1), ylim=c(0,1)) removed. Plot without xlim and ylim

I have tried to increase the space between the facets, but so far I have been unable to do it. Do you have any advice?

I use ggplot2 version 0.9.1 .

like image 713
Timo Avatar asked Oct 02 '12 14:10

Timo


2 Answers

for 0.9.1 use: p + opts(panel.margin = unit(2, "lines")) but you have a lot of extra white space and IMO lose some of the effect of the faceting (note 0.9.2 now uses theme instead of opts)

Over the years the ggplot2 API has changed, as of 2018-02-01 this is the updated solution:

p + theme(panel.spacing = unit(2, "lines"))
like image 165
Tyler Rinker Avatar answered Oct 10 '22 19:10

Tyler Rinker


Building upon Tyler's answer, you can further squeeze the facet panels together using the strip.text theme parameter as follows:

library(tidyverse)

mpgTidy <- pivot_longer(mpg, c(cty, hwy), names_to="mpg_categ", values_to="mpg")

g <- ggplot(mpgTidy, aes(x=displ, y=mpg, color=factor(cyl))) +
  facet_wrap(~ mpg_categ) +
  geom_point()

g

enter image description here

g + theme(strip.text=element_text(margin=margin()),
          panel.spacing=unit(0, "lines"))

enter image description here

This can be useful when facet labels are long or include newlines and the faceted plot has both rows and columns.

like image 26
Megatron Avatar answered Oct 10 '22 18:10

Megatron