3

In short: I would like to have separate legends for each "panel" of two-panel plot made using facet_wrap . Using facet_wrap(scales="free") works fine for when I want different axis scales, but not for the size of points.

Background: I have data for several samples with three measurements each: x, y, and z. Each sample is from either class 1 or class 2. x and y have the same distributions in each class. However, all the z measurements for class 1 are less than 1.0; z measurements for class 2 range from 0 to 100.

Where I'm stuck: Plot x and y on the x and y axes, respectively. Make the area of each point proportional to its z value.

d = matrix(c(runif(100),runif(20)*100),ncol=3)
e = data.frame( gl(2,20), d )
colnames(e) = c("class","x","y","z")
ggplot( data = e, aes(x=x, y=y, size=z) ) + 
  geom_point() + scale_area() +
  facet_wrap( ~ class, ncol=1, scales="free" )

enter image description here

Problem: Note that the dots on the first panel are difficult to see because they are on the very low end of the scale used for the single legend which ranges from 0 to 100. Is it even possible to have two separate legends (each with a different range) or should I make two plots and combine them with viewports?

Brian Diggs
  • 57,757
  • 13
  • 166
  • 188
kdauria
  • 6,300
  • 4
  • 34
  • 53
  • It won't be possible. This is a design feature of `ggplot2`. Use `gridExtra` and `grid.arrange` instead of `facet_wrap` – mnel Nov 27 '12 at 23:10
  • 2
    @mnel Saying something is impossible is just _begging_ for kohske to show up and demonstrate otherwise. That said, I agree that `grid.arrange` is obviously the right path. – joran Nov 27 '12 at 23:12

1 Answers1

5

A solution using grid.arrange. I've left in the call to facet_wrap so the strip.text remains. You could easily remove this.

# plot for class 1
c1 <- ggplot(e[e$class==1,], aes(x=x,y=y,size=z)) + geom_point() + scale_area() + facet_wrap(~class)
# plot for class 2
c2 <- c1 %+% e[e$class==2,]

library(gridExtra)

grid.arrange(c1,c2, ncol=1)

enter image description here

mnel
  • 113,303
  • 27
  • 265
  • 254
  • Thanks! According to other comments, using facet_wrap just isn't possible and I can understand why. Too many legends could easily become too messy. I will use viewports and grid.arrange to solve my problem. Thanks everyone. – kdauria Nov 27 '12 at 23:23
  • `facet_wrap` is working here, but only on a subset of the data. The only reason I've kept it in is to retain the `strip.titles` Each plot is a faceted plot with 1 facet. – mnel Nov 27 '12 at 23:39