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.
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.
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 .
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"))
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
g + theme(strip.text=element_text(margin=margin()),
panel.spacing=unit(0, "lines"))
This can be useful when facet labels are long or include newlines and the faceted plot has both rows and columns.
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