I have some x and y data that I would like to compare on a ggplot2 scatter plot. I would like to add a unity line (y = x), twofold (y = 2x), half (y = x/2) and smoother lines to help making sense of the data but I cannot find how to add theses lines to the plot's legend. Any idea?
set.seed(123)
x <- runif(20, 1, 10)
y <- 0.8 * x + runif(20, -1, 1)
cat <- factor(c(rep("high", 10), rep("low", 10)))
d <- data.frame(x, y, cat)
ggplot(data=d) +
geom_point(aes(x, y, colour=cat)) +
geom_abline(aes(intercept=0, slope=1), col = "red") +
geom_abline(aes(intercept=0, slope=0.5), col="blue", linetype="dotted") +
geom_abline(aes(intercept=0, slope=2), col="blue", linetype="dashed")+
geom_smooth(aes(x, y))
y vs x scatter plot in ggplot2
I would like the labels 'unity line', 'twofold', 'half', and 'smoother' to appear below the 'high' and 'low' labels in the legend.
Following User3640617's answer, I have tried the following code but the result is still not satisfying because the data points now have a linetype and a smoothing linetype linked to them in the legend.
ggplot(data=d) +
geom_point(aes(x, y, colour=cat)) +
geom_abline(aes(intercept=0, slope=1, colour="y = x")) +
geom_abline(aes(intercept=0, slope=.5, colour="y = x/2")) +
geom_abline(aes(intercept=0, slope=2, colour="y = 2x")) +
geom_smooth(aes(x,y, colour="smooth")) +
scale_color_manual(
values=c("red", "darkgreen", "black", "blue", "red", "blue")) +
scale_linetype_manual(
values=c("blank", "blank", "solid", "dashed", "solid", "dotted")) +
scale_shape_manual(values=c(1, 1, NA, NA, NA, NA))
Also, I do not seem to be able to manually change the tinetypes:
scatter plot with ablines and smoother
I know, I could simply choose other colors and there would be less confusion but it should be possible to have a legend with only points for points and lines for lines instead of having point and lines for both points and lines, or is it not?
ggplot2 seems to be bothered by the addition of color
or linetype
after the aes
. The order of the categories seems to be changed when adding the lines to the legend.