2

in the following sample data , how can i display the abline ( i e the red color line) in legend with y. my code and data:

x<-c(1990,1991,1992,1993,1994,1995)
y<-c(400,500,465,450,550,555)

df<-data.frame(x,y)
df
plot1<- ggplot(df, aes(x)) +
        geom_line(size=0.5,lty="dashed", aes(y=y),color="Blue") +
        geom_abline(aes(slope=-0.62,intercept=1670,colour="break"),size=0.9)+
        geom_point(aes(y=y,shape="y"),size=4, color="Gray24",fill="Green")
plot1

. what i got is the belowenter image description here image. i need the red line to be displayed in legend

talat
  • 68,970
  • 21
  • 126
  • 157
Cirrus
  • 638
  • 3
  • 13
  • 26

1 Answers1

4

You can use the show_guide=TRUE argument:

plot1<- ggplot(df, aes(x)) +
  geom_line(size=0.5,lty="dashed", aes(y=y),color="Blue") +
  geom_abline(aes(slope=-0.62,intercept=1670,colour="break"), size=0.9,show_guide = TRUE)+
  geom_point(aes(y=y,shape="y"),size=4, color="Gray24",fill="Green")

You'll probably need to change the labels in the legend, but you should be able to do that with theme.

Edit: To remove the slash from the legend, you can use guides and override.aes:

plot1 <- ggplot(df, aes(x, y)) +
  geom_point(aes(shape = "y"), size = 4, color = "Gray24", lty = 0) +
  geom_line(size = 0.5, lty = "dashed", color = "Blue") +
  geom_abline(aes(slope = -0.62, intercept = 1670, colour = "break"), size = 0.9, 
               show_guide = TRUE) +
  guides(shape = guide_legend(override.aes = list(linetype = 0)))
IRTFM
  • 258,963
  • 21
  • 364
  • 487
tkmckenzie
  • 1,353
  • 1
  • 10
  • 19
  • Thank you tkmckenzie, But that do not give wnhat i want. it overlaps the points with line. you can run and see the overlap of line and points. SO it is not what i expect. do you know how to remove that overlap. – Cirrus Jul 17 '14 at 20:36
  • @Cirrus The fix for that is a little hacky and involves using `guides` and `override.aes`, but I've posted it in an edit above, hopefully that'll give you what you're looking for. – tkmckenzie Jul 17 '14 at 22:54
  • This can happen: `show_guide` has been deprecated. Please use `show.legend` instead. On the other hand, in my case, I had no luck using ``show.legend`` whereas ``show_guide`` produced the error message but still gave me the legend... – PatrickT Sep 30 '17 at 11:45