4

I am trying to show a line graph with some vertical lines as indicators of particular time points and have a legend labeling those time points.

Based on the example in section 6.4.4 of the book ggplot2, I've tried the following

huron<-data.frame(year=1875:1972,level=LakeHuron)

vertDf<-data.frame(years=c(1900,1925,1950),labels=c("A","B","C"))

pltWithLines<-ggplot(huron, aes (x=year,y=level)) +
                              geom_line() + 
                              geom_vline(aes(xintercept=years,color=labels),data=vertDf) + 
                              scale_color_manual("Sample Year",
                                      values=c("A"="blue","B"="red","C"="green"))

This produces a graph with the vertical lines having the correct color, but no legend at all.

What is wrong with this?

Peter N. Steinmetz
  • 1,252
  • 1
  • 15
  • 23

1 Answers1

6

you need show_guide

ggplot(huron, aes (x=year,y=level)) +
  geom_line() + 
  geom_vline(aes(xintercept=years, color=labels),data=vertDf, show_guide=T) + 
  scale_color_manual("Sample Year",
                     values=c("A"="blue","B"="red","C"="green"))
jalapic
  • 13,792
  • 8
  • 57
  • 87
  • That works, thanks. It is weird with the documentation on this. The first few times I looked for documentation of show_guide in the help for geom_vline, I didn't see it. I think that is because the arguments in the function prototype are not in the same order as the listing of them. – Peter N. Steinmetz Mar 05 '15 at 23:05
  • 1
    `show_guide` has been deprecated in favour of `show.legend` – Alex Aug 22 '18 at 06:27