Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

r - How to add legend for vertical lines in ggplot?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...