Plotting lines in ggplot2 with given slope and intercept with legend

Viewed 7457

I have a dataframe containing columns for slope and intercept. I want to plot lines corresponding to each intercept and slope for a given range and assign them color using a 3rd column. As I don't know how to plot geom_abline without assigning a plot to ggplot first, I used other columns x and y to get a plot and adjust the axis scale to see the abline lines and hide x y plot. So far so good. However, when I try to use color for abline, I can see the lines in different colors but I don't see the legend labels. Here is my sample code:

slope <- c(rep(.28,5),rep(.26,5),rep(.27,5),rep(.28,5),rep(.24,5))
intercept <- c(rep(-2.5,5),rep(-1.7,5),rep(-1.63,5),rep(-1.5,5),rep(-1.58,5))
wf <- c(1,1,1,1,1,5,5,5,5,5,8,8,8,8,8,18,18,18,18,18,22,22,22,22,22)
x <- c(seq(1:5),seq(1:5),seq(1:5),seq(1:5),seq(1:5))
y <- c(seq(1:25))
df <- data.frame(cbind(slope,intercept,wf,x,y))

ggplot(data=df,
   aes(x,y))+
  geom_point()+
  theme_bw() +
  scale_y_continuous(limits=c(-3,0))+
  geom_abline(data=df,aes(slope=slope,intercept=intercept,color=factor(wf)))

Here is the plot I get using the above code enter image description here

I also tried to use scale_color_manual(labels=c("1","5","8","18","22")) to manually add the labels but it does not work.

Please help me to add labels or better how to plot lines with given slope and intercept to ggplot without having to fool around with other data.

0 Answers
Related