Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top