Reputation: 6326
If I have two datasets on the same plot, can I have two independent facets on that plot, each corresponding to a different data set?
For example, in a scatter plot, one can split one data in the x direction, one can split the other data set in the y direction.
Consider, for example, the following code, where I am trying to split d1
for values of the X axis less than 0.5 and bigger than 0.5,
and similarly for d2
and the y axis. This runs, but I don't understand why I get the result i do.
It is possible that ggplot2
is simply not designed to do this. I don't have an application in mind, I'm just trying to understand the
limits of faceting, and playing with examples is easier than trying to understand the code.
library("ggplot2")
splitvec <- function(v)
{
if(v<0.5)
return("L")
else if(v>=0.5)
return("R")
}
set.seed(1)
x1 <- runif(5, 0, 1)
y1 <- runif(5, 0, 1)
xsplit <- sapply(x1, splitvec)
d1 = data.frame(x=x1, y=y1, X=xsplit)
x2 <- runif(5, 0, 1)
y2 <- runif(5, 0, 1)
ysplit <- sapply(y2, splitvec)
d2 = data.frame(x=x2, y=y2, Y=ysplit)
r = ggplot() +
geom_point(data=d1, aes(x=x, y=y)) + facet_grid( ~ X) +
geom_point(data=d2, aes(x=x, y=y)) + facet_grid(Y ~ .)
Upvotes: 3
Views: 3585
Reputation: 121568
In this case you can do something like :
facet_grid(Y~X)
Since that grid faceting is applied sequentially. Note that you can't use facet_wrap
in this case.
Here I am rewriting your code to use different factors for each split variable (X,Y).
d1$X <- ifelse(d1$x<0.5,'d1.L','d1.R')
d2$Y <- ifelse(d2$x<0.5,'d2.L','d2.R')
It is better to use different colors for each data to understand what happens to your data.
r = ggplot() +
geom_point(data=d1, aes(x=x, y=y),col='blue',size=10) +
geom_point(data=d2, aes(x=x, y=y))+
facet_grid(Y~X,scales="free")+
theme(strip.text = element_text(size=20))
Upvotes: 4