ggplot2() with multiple geom_line calls, how to create a legend with matching colors?

Hello,

First question as a new member: I have a graph with four lines (4 curves, code is below) and I want to create a legend that correspond to the colors I am using. I am trying to use scale_color_manual as demonstrated in this tutorial ( http://r-statistics.co/Complete-Ggplot2-Tutorial-Part2-Customizing-Theme-With-R-Code.html ). Note: the letter W X Y Z are just placeholders, for now.

However, no legend is showing up on my graph. Any help would be appreciated.

require(ggplot2)
library(grid)

x <- theta_vec
df <- data.frame(x,likelihood_mtrx)
names(df)[1] <- "theta"
names(df)[2] <- "pattern1"
names(df)[3] <- "pattern2"
names(df)[4] <- "pattern3"
names(df)[5] <- "pattern4"
df

number_ticks <- function(n) {function(limits) pretty(limits, n)}
gg1 <- ggplot(df, aes(x)) +
geom_line(aes(y=likelihood_mtrx[,1]), colour="black") + # first layer
geom_line(aes(y=likelihood_mtrx[,2]), colour="green") + # second layer
geom_line(aes(y=likelihood_mtrx[,3]), colour="blue") + # third layer
geom_line(aes(y=likelihood_mtrx[,4]), colour="red") + # fourth layer
labs(title="Brute Force Estimation", x="Trait Level (\u03b8)", y="Response Pattern Likelihood") +
scale_x_continuous(breaks=number_ticks(10)) + # 10 looks good, not sure why
theme(legend.position="top") +
scale_color_manual(name="Liklihood",
labels = c("W",
"X",
"Y",
"Z"),
values = c("W"="blue",
"X"="red",
"Y"="green",
"Z"="orange"))
print(gg1)

If you want a legend then you have to map the aesthetic attribute "color" to a variable (or in this case a value), so you have to put it inside the aes() function, try this way

geom_line(aes(y=likelihood_mtrx[,4], colour="X")) + # fourth layer

If you need more specific help please provide a proper REPRoducible EXample (reprex)

1 Like