r - ggplot2: Save individual facet_wrap facets as separate plot objects -
i big fan of facet_wrap
. though fast split big data frame , plot several plots , explore within r, it's not best tool presenting in paper or power point. find myself wasting lot of time scales, binwidths , font sizes , modifying on inkscape plot.
sometimes subset data frame many data frames , plot individually each one. later join them multiplot
or hand.
i wondering if there might way of making ggplot call in same way (one big df factor column used faceting) or way make ggplot read list-like data frame separated faceting factor. ideal output should multiple single plots i'll edit later on inkscape (and use free_y
scales make less painful)
to clear,
df<-mtcars ggplot(df,aes(df$mpg,df$disp,color=factor(cyl)))+ geom_point(aes(df$mpg,df$disp))+ facet_wrap( ~cyl)
produces 1 plot. desired output in case 3 plots, 1 each facet.
you can use lapply
create list 1 plot each value of cyl
:
# create separate plot each value of cyl, , store each plot in list p.list = lapply(sort(unique(mtcars$cyl)), function(i) { ggplot(mtcars[mtcars$cyl==i,], aes(mpg, disp, colour=factor(cyl))) + geom_point(show.legend=false) + facet_wrap(~cyl) + scale_colour_manual(values=hcl(seq(15,365,length.out=4)[match(i, sort(unique(mtcars$cyl)))], 100, 65)) })
the complicated scale_colour_manual
argument way color point markers same way colored if values of cyl
included in single call ggplot
.
update: address comments, how this:
# fake data set.seed(15) dat = data.frame(group=rep(c("a","b","c"), each=100), value=c(mapply(rnorm, 100, c(5,10,20), c(1,3,5)))) p.list = lapply(sort(unique(dat$group)), function(i) { ggplot(dat[dat$group==i,], aes(value, fill=group)) + geom_histogram(show.legend=false, colour="grey20", binwidth=1) + facet_wrap(~group) + scale_fill_manual(values=hcl(seq(15,365,length.out=4)[match(i, sort(unique(dat$group)))], 100, 65)) + scale_x_continuous(limits=range(dat$value)) + theme_gray(base_size=15) })
the result below. note code above gives same x-scale on 3 graphs, not same y-scale. same y-scale, can either hard-code as, say, scale_y_continuous(limits = c(0,35))
, or can find maximum count programmatically whatever binwidth set, , feed scale_y_continuous
.
# arrange 3 plots library(gridextra) do.call(grid.arrange, c(p.list, nrow=3))
Comments
Post a Comment