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

Cha*_*imm 1 r ggplot2

我一直在互联网上搜索我的问题的答案,但到目前为止,我发现所有人都提出同样的问题,但与我有不同的情况.

大多数人在他们的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))
Run Code Online (Sandbox Code Playgroud)

我对R和ggplot(我3天前刚开始)相当新,所以我的代码可能不是最有效的方法,但它完成了工作.

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

jor*_*ran 6

抛弃你的整个长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))
Run Code Online (Sandbox Code Playgroud)

您可以通过设置颜色scale_color_manual(假设GS_Field是一个因素,我想).

这里的想法是,当你在内部绘制美学时,ggplot会自动尝试生成一个图例aes().否则你就是在设定美学.