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

如何使用R在ggplot2中添加图例?,r,ggplot2,R,Ggplot2,我一直在互联网上搜索我的问题的答案,但到目前为止,我所找到的都是问同一个问题的人,但他们的情况与我不同 大多数人在他们的ggplot上有两个或两个以上的数据集,并且正在添加一个图例来显示哪个是哪个。一、 但是,绘制一条直线,但该直线内有多种颜色 以下是我的输出图片,以进一步澄清: 我想创建一个图例来指定每种颜色的含义 这是我的密码: p04 <- read.csv("p04_datalog.csv",header=TRUE) #The following line activates

我一直在互联网上搜索我的问题的答案,但到目前为止,我所找到的都是问同一个问题的人,但他们的情况与我不同

大多数人在他们的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))

p04放弃你的整个long
ifelse
monstrosity,只需将
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\u color\u manual
设置颜色(假设
GS\u Field
是一个因素)


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

放弃整个long
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\u color\u manual
设置颜色(假设
GS\u Field
是一个因素)

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