I have been struggling with creating a legend in my ggplot for some time now, and I cannot find any answer that works.
This is the stripped down version of my ggplot:
ggplot()
geom_smooth(data = mydf1, aes(x, predicted, linetype = 1), method = "lm", linetype = 1, colour = "black")
geom_smooth(data = mydf2, aes(x, predicted, linetype = 2), method = "lm", linetype = 2, colour = "black")
geom_smooth(data = mydf3, aes(x, predicted, linetype = 3), method = "lm", linetype = 3, colour = "black")
theme_classic()
As you can notice, I am taking data from different dataframes (mydf1, mydf2, mydf3). Now I want to manually add a legend that specifies that the solid line is "Group 1", the longdashed line is "Group 2", and the dotted linetype is "Group 3". However, whatever I try, no legend appears in my ggplot. I included linetype within the aes(), tried everything I could think of regarding scale_linetype_manual(), and I've been looking around to find solutions, but no legend pops up.
Am I missing something obvious? I just need a small legend to the side stating what the different linetypes mean.
My data is the following:
mydf1 <- data.frame(x = c(seq(-1,1, 0.2)),
predicted = c(-0.27066438, -0.23568714, -0.20070991, -0.16573267, -0.13075543, -0.09577819, -0.06080095, -0.02582371, 0.00915353, 0.04413077, 0.07910801))
mydf2 <- data.frame(x = c(seq(-1,1, 0.2)),
predicted = c(-0.39806988, -0.34348641, -0.28890295, -0.23431948, -0.17973602, -0.12515255, -0.07056909, -0.01598562, 0.03859784, 0.09318131, 0.14776477))
mydf3 <- data.frame(x = c(seq(-1,1, 0.2)),
predicted = c(-0.25520076, -0.22917917, -0.20315758, -0.17713600, -0.15111441, -0.12509282, -0.09907123, -0.07304964, -0.04702806, -0.02100647, 0.00501512))
Although any practical solution would be helpful, I am not neccesarily looking to combine the dataframes into a single one and redo the ggplot. Thanks!
CodePudding user response:
Bring the line linetype inside aes() and use lab() to give title for the legend.
ggplot()
geom_smooth(data = mydf1, aes(x, predicted, linetype = "Group 1"), method = "lm", colour = "black")
geom_smooth(data = mydf2, aes(x, predicted, linetype = "Group 2"), method = "lm", colour = "black")
geom_smooth(data = mydf3, aes(x, predicted, linetype = "Group 3"), method = "lm", colour = "black")
labs(linetype="Group")
theme_classic()
CodePudding user response:
Here is an alternative way using bind_rows
:
library(dplyr)
library(ggplot2)
bind_rows(mydf1, mydf2, mydf3) %>%
mutate(group = as.integer(gl(n(), 11, n()))) %>%
ggplot(aes(x, predicted, linetype=factor(group)))
geom_smooth(color="black", method = "lm", se=F)
scale_linetype_discrete(name="group",
breaks=c(1, 2, 3),
labels = c("group1", "group2", "group3"))
theme_classic()