i'm trying connect ggplot2 boxplots geom_lines multiple factors. i'd been able accomplish far connect boxplot lines, see attach picture. wish connect boxplots corresponding factor.
for example variable fl, want connect 2 boxplot, without connecting them remaining variables. variable rw, connecting 2 sex boxplot without remaining others.
library("mass") data(crabs) melt_crabs <- melt(crabs,id.var=c("sp","sex","index")) ggplot(melt_crabs, aes(x = variable, y = value)) + geom_line(aes(group = index), size = 0.05, alpha = 0.7) + geom_boxplot(aes(fill = sp), alpha = 0.5) + facet_grid(sex~.)
does know how achieve this? hope i'd explain myself clear way.
many , best wishes,
@stibu's answer quickest , cleanest way desired output. building off answer, since given variable, plots no longer next each other, might want put each in own separate plot. can minor tweak facet_grid
call in @stibu's code:
ggplot(melt_crabs, aes(x = interaction(sex, variable), y = value)) + geom_boxplot(aes(fill = sex), alpha = 0.5) + geom_line(aes(group = interaction(index, variable)), alpha = 0.5, colour = "darkgrey") + facet_grid(sp~variable,scales="free_x") + scale_x_discrete(labels = "")
also did digging if want move top strip bottom, isn't difficult. adapting code from: how display strip labels below plot when faceting?
we get:
p<-ggplot(melt_crabs, aes(x = interaction(sex, variable), y = value)) + geom_boxplot(aes(fill = sex), alpha = 0.5) + geom_line(aes(group = interaction(index, variable)), alpha = 0.5, colour = "darkgrey") + facet_grid(sp~variable,scales="free_x") + scale_x_discrete(labels = "") # convert plot grob gt <- ggplotgrob(p) # positions of panels in layout: t = top, l = left, ... panels <-c(subset(gt$layout, name == "panel", select = t:r)) # strip grob & x-axis label grob stripgrob = gtable_filter(gt, "strip-top") #replace x-axis ticks strip gt = gtable_add_grob(gt, stripgrob, t = max(panels$b)+1, l = min(panels$l), r = max(panels$r)) # remove old strip gt = gt[-(min(panels$t)-1), ] grid.newpage() grid.draw(gt)
Comments
Post a Comment