如何在ggplot中添加垂直线的图例? [英] How to add legend for vertical lines in ggplot?

查看:132
本文介绍了如何在ggplot中添加垂直线的图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用一些垂直线条作为特定时间点的指标来显示线条图,并且有一个图例标记这些时间点。



根据ggplot2第6.4.4节中的示例,我尝试了以下内容:

<$ p (year = 1875:1972,level = Lake Huuron)

vertDf< -data.frame(年= 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=蓝色,B=红色,C=绿色))

产生一个图表,垂直线的颜色是正确的,但没有传说。



这有什么问题?

解决方案

您需要 show_guide

  ggplot(huron,aes(x = year,y = level))+ 
geom_line()+
geom_vline(aes(x data = vertDf,show_guide = T)+
scale_color_manual(Sample Year,
values = c(A=blue,B=红色,C=绿色))


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?

解决方案

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

这篇关于如何在ggplot中添加垂直线的图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆