繁体   English   中英

如何使用R在ggplot2中添加图例?

[英]How do I add a legend in ggplot2 using R?

我一直在互联网上搜寻我的问题的答案,但到目前为止,我所发现的只是那些提出相同问题但与我相比情况不同的人。

大多数人的ggplot上有两个或更多数据集,并添加了图例以显示哪个是哪个。 但是,我只画了一条线,但是线内有多种颜色。

这是我的输出的图片,以供进一步说明:

在此处输入图片说明

我想创建一个图例以指定每种颜色的含义。

这是我的代码:

p04 <- read.csv("p04_datalog.csv",header=TRUE)

#The following line activates the ggplot2 add-on
library(ggplot2)

#This line will eliminate all -1 values for GS_ReelRaiseLowerAngle
p04_NoNegative <- subset(p04, p04$GS_ReelRaiseLowerAngle != -1)

#This creates an array of colors that are to be used with the plotting scripts

fieldcolors <- ifelse(p04_NoNegative$GS_Field == "Out of Bounds","black",ifelse(p04_NoNegative$GS_Field ==
 "Clumping","Orange",ifelse(p04_NoNegative$GS_Field == "Down","purple",ifelse(p04_NoNegative$GS_Field == 
 "High Moisture","darkblue",ifelse(p04_NoNegative$GS_Field == "High Thin","pink",ifelse(p04_NoNegative$GS_Field == 
 "High Weeds","green",ifelse(p04_NoNegative$GS_Field == "Low Moisture","cyan",ifelse(p04_NoNegative$GS_Field == 
 "Low Thin","white",ifelse(p04_NoNegative$GS_Field == "Low Weeds","green4",ifelse(p04_NoNegative$GS_Field == 
 "Medium Thin","red",ifelse(p04_NoNegative$GS_Field == "Medium Weeds","yellowgreen",ifelse(p04_NoNegative$GS_Field == 
 "Short Hieght","tan2",ifelse(p04_NoNegative$GS_Field == "Tall Hieght","tan","brown")))))))))))))

x_axis <- seq(0,6000,10)
x_axis_ef <- seq(0,6000,500)

#The following lines generate a line plot of reel height for the entire field with colors
ggplot(p04_NoNegative, aes(x=Distance.Traveled, y=GS_ReelRaiseLowerAngle)) + 
  geom_line(color=fieldcolors,size=1.1) + ggtitle("p04 entire field") + ylim(0,0.6) +
  ylab("Reel Height (angle)")+ xlab("Distance (m)") + 
  scale_x_continuous(breaks = x_axis_ef) + coord_cartesian(xlim = c(0,5000))

我是R和ggplot的新手(我是3天前才开始的),所以我的代码可能不是最有效的方法,但可以完成工作。

我需要添加一个图例,以便阅读图形的人可以知道每种颜色代表什么。 例如 鲜绿色代表“高杂草”。

ifelse整个漫长的ifelse然后将ggplot调用修改为:

ggplot(p04_NoNegative, aes(x=Distance.Traveled, y=GS_ReelRaiseLowerAngle)) + 
  geom_line(aes(color=GS_Field),size=1.1) + 
  ggtitle("p04 entire field") + ylim(0,0.6) +
  ylab("Reel Height (angle)")+ xlab("Distance (m)") + 
  scale_x_continuous(breaks = x_axis_ef) + 
  coord_cartesian(xlim = c(0,5000))

您可以通过scale_color_manual设置颜色(假设GS_Field是一个因素)。

这里的想法是,当您在aes()内部映射美学时,ggplot会自动尝试生成图例。 否则,您将设置美学。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM