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.7k views
in Technique[技术] by (71.8m points)

ggplot2 - How to add legend to ggplot manually? - R


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

1 Reply

0 votes
by (71.8m points)

ggplot really only likes to draw legends for things that have aesthetic mappings. If you set "code names" for colors, you can define them in a manual scale for that attribute. For example

ggplot(df, aes(x = instance, y = total_hits)) +
  geom_point(size = 1) + 
  geom_line()+
  geom_line(aes(x=instance, y = line1, colour="myline1")) +
  geom_vline(xintercept=805) + 
  geom_line(aes(x=instance, y = line2, colour="myline2"))+
  geom_line(aes(x=instance, y = line3, colour="myline3")) +
  scale_colour_manual(name="Line Color",
      values=c(myline1="red", myline2="blue", myline3="purple"))

should work (untested since you didn't provide any data at all). Anytime you ask a question, it's just polite to include a reproducible example so the answer-er doesn't have to do all the work themselves to test.


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

...