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

时间:2015-06-05 16:17:58

标签: r ggplot2

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

大多数人在他们的ggplot上有两个或更多数据集,并添加一个图例来显示哪一个是哪个。但是,我绘制了一条线,但线内有多种颜色。

以下是我的输出图片,以便进一步说明:

enter image description here

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

这是我的代码:

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天前刚开始)相当新,所以我的代码可能不是最有效的方法,但它完成了工作。

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

1 个答案:

答案 0 :(得分: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))

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

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