While there are some topics going in the same general direction, I haven't found any that would deal with my issue specifically. Hence a new topic, and thanks in advance for all the help.
Situation
I have two plots, that need to go in a single figure horizontally, e.g.:
library(ggplot2)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(price, carat, data=dsamp, colour=clarity)
p2 <- qplot(price, depth, data=dsamp, colour=clarity)
While the dependent variable differs per plot, the grouping and the independent remains the same. Hence I only need but a single legend in the figure to describe the groups.
What I have tried and what did not work
I have tried to use the solution as described in the R Cookbook. The custom multiplot()
function given on that page renders the plots without legends just fine. However, if one needs only a single legend, that function fails. Since one of the graphs would contain the legend, whereas the other not, the width of both graphs would differ in relation to each other (copy the multiplot function from the link mentioned please):
multiplot(p1 + theme(legend.position = "none"),p2,cols=2)
Another potential solution that I have found is the package gridExtra
, with this code example. It almost does what I need, except that the graphs are arranged vertically. I tried playing with the function arguments, but could not figure how to arrange the plots horizontally. Hope someone has more experience with that package/issue. Thanks!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…