Suppose I have the following data which summarizes the values of a dependent variable (dv) at low and high vales of a predictor (x) and a moderator (z)
dfx <- data.frame(x = rep(c(-0.909, 0.909),2),
z = c(-0.676, -0.676, 0.676, 0.676),
dv = c(448.8, 464.4, 462.8, 472.1))
I would like to draw the dv as a function of the predictor and the moderator by customizing both the type of lines and the markers
library(ggplot2)
dfx$z <- as.factor(dfx$z) # turn the moderator as a factor
ggplot(dfx, aes(x=x, y = dv, colour=z, shape=z))+
geom_line()+
geom_point()+
scale_y_continuous("dv", limits = c(440,480))+
theme_classic()+
scale_colour_manual ("A title", values=c("black", "black"), labels=c("-1SD", "+1SD"))+
scale_shape_manual ("A title", values=c(2,15),labels=c("-1SD","+1SD"))
However, I would like to customize the linetype as well.
When I add:
ggplot(dfx, aes(x=x, y = dv, colour=z, shape=z, linetype=z)
the following plot emerges. Yet I cannot either hide the second label or customize it through scale_linetype_manual
Is there a way to fix this? I searched the community but could not find any method to overcome this problem. Also, when I suppress the second label, the legend key does not show the line type and mark. Any hint will be very much appreciated.
Use:
library(ggplot2)
ggplot(dfx, aes(x=x, y = dv, shape = z, linetype = z)) +
geom_line() +
geom_point() +
scale_y_continuous("dv", limits = c(440, 480)) +
theme_classic() +
scale_linetype_manual("A title",
values = c(1, 3),
labels = c("-1SD", "+1SD")) +
scale_shape_manual("A title",
values = c(2, 15),
labels = c("-1SD", "+1SD"))
The default behaviour for ggplot()
is to add anything declared inside aes()
to the legend. You can suppress aesthetics from a legend using guides(colour = "none")
or show.legend = FALSE
. In your case, you were using colour
, so removing it was the better solution.