2015-06-05 108 views
1

我一直在尋找互聯網上的問題的答案,但到目前爲止,我發現所有人都問同樣的問題,但有不同的環境,然後我。如何使用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天前),所以我的代碼可能不是最有效的方法,但它能夠完成任務。

我需要添加一個圖例,以便閱讀圖形的人可以知道每種顏色代表什麼。恩。鮮綠色代表「高雜草」。

回答

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自動嘗試生成一個圖例。否則你是設置的審美。

相關問題