0

I am trying to make group boxplots displayed in a grid layout and I'd like a common legend for each group displayed on the side. I already did this for one subset of the data, here's an example of the code

group.colors=c("V"= "#F8766D", "W"= "#619CFF", "X" ="#00BA38", "Y"="#E69F00", "Z"="#999999")

g1=ggplot(data=df[df$analyte=="BP3",], aes(x=analyte, y=concentration, fill=Lab_ID))+geom_boxplot(outlier.shape = NA)+geom_point(aes(group=Lab_ID),position=position_dodge(width=0.75), size=1.5, alpha=.9)+theme_bw()+theme(legend.position = "none")
g1=g1+scale_fill_manual(values=group.colors)+ylab("concentration (ng/mL)")+xlab("")

g2=ggplot(data=df[df$analyte=="BPA",], aes(x=analyte, y=concentration, fill=Lab_ID))+geom_boxplot(outlier.shape = NA)+geom_point(aes(group=Lab_ID),position=position_dodge(width=0.75), size=1.5, alpha=.9)+theme_bw()+theme(legend.position = "none")
g2=g2+scale_fill_manual(values=group.colors)+ylab("concentration (ng/mL)")+xlab("")

f=ggarrange(g1,g2,nrow=1,ncol=2, common.legend=TRUE, legend="right")
annotate_figure(f,top= text_grob("Title", face = "bold", size = 16))

For some reason when I use the same code on a different set of analytes,the legend is not listing all of the groups even though the groups are in the boxplots

I tried including limits in scale_fill_manual but it did nothing

Gingerhaze
  • 664
  • 2
  • 5
  • 13
  • Does the problem have anything to do with `ggarrange`? That is, does `g2` look good by itself, but then when you `ggarrange` it with `g1`, the `g2` legend loses some items? – Gregor Thomas Nov 06 '19 at 21:34
  • I think, to help you, we'd need a reproducible sample of data demonstrating the problem... – Gregor Thomas Nov 06 '19 at 21:36
  • @Gregor Yes, that is correct. If I plot the figure by itself the legend looks correct, its only when I use ggarrange that the legend loses items – Gingerhaze Nov 06 '19 at 21:39
  • 2
    From what I get from your question, your problem could also easily be fixed by facetting on the `analyte` variable. Could you motivate why a facet is insufficient? – teunbrand Nov 06 '19 at 21:46
  • @teunbrand The scale on the y axes are different for some of the figures – Gingerhaze Nov 07 '19 at 12:58
  • 1
    Facets can probably handle this by using the `scales = "free_y"` argument – teunbrand Nov 07 '19 at 13:19
  • Okay. Well, we can't see or reproduce the problem, or try possible solutions, without a sample of data demonstrating the problem. Please provide that for additional help. See the [FAQ on making reproducible examples in R](https://stackoverflow.com/a/5963610/903061) if you need help with that - `dput` is a nice way to share copy/pasteable data. Something like `dput(df[1:10, ])` for the first 10 rows (but you may need to select more than 10 rows to show the issue). – Gregor Thomas Nov 07 '19 at 14:05

0 Answers0