Reputation: 1788
I'm trying to plot a 4-way interaction from a factorial experiment using ggplot2
with geom_line()
and geom_point()
.
Data I'm working with is emmeans()
object with marginal means estimated from a linear mixed-effects model.
And the graph I can get via emmip()
is this:
What I'd like is to separate b:c
interaction so that one factor is defined by color and / or point type and the other by linetype (dashed vs. solid)
A minimal example is this:
df<- data.frame(y=rnorm(n=16),
a=gl(2,4,16, labels=c("a1","a2")),
b=gl(2,2,16, labels=c("b1", "b2")),
c=gl(2,1,16, labels=c("c1", "c2")),
fac=gl(2,8,16, labels=c("panel1", "panel2")))
I tried the following ggplot()
code:
ggplot(df, aes(y=y, x=a, color=b)) +
geom_point(aes(shape=b), size=3) +
geom_line(aes(linetype=c)) +
facet_wrap(~fac)
But I get a warning that I don't know how to handle:
geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?
geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?
And the graph looks almost as intended, but without the c
factor horizontal lines drawn between corresponding b
points:
How can I fix this?
I found a similar question dealing directly with predicted values from a lmer()
object: How to plot mixed-effects model estimates in ggplot2 in R? but still can't find a way to deal with my data format.
Upvotes: 3
Views: 3768
Reputation: 1788
Following Z.Lin comment above I found what I was looking for with:
ggplot(df, aes(y=y, x=a)) +
geom_point(aes(color=b),size=3) +
geom_line(aes(group = b:c, color=b, linetype=c), size=1) +
facet_wrap(~fac)
Upvotes: 3
Reputation: 2864
One problem with your example is that you use both color and shape aesthetics for the variable b. I would recommend to choose one and save the other for the variable c rather than using lines. Generally speaking, using lines makes sense for continuous variables and trends. You can use one of the following:
# colored by b & shaped by c
ggplot(df, aes(y=y, x=a, color=b)) +
geom_point(aes(shape=c), size=3) +
facet_wrap(~fac)
# colored by c & shaped by b
ggplot(df, aes(y=y, x=a, color=c)) +
geom_point(aes(shape=b), size=3) +
facet_wrap(~fac)
Upvotes: 0