2015-09-28 34 views
1

我有一個數據集,包括三個連續橫斷的魚類的累積計數,所以這包括3列(物種,計數,橫斷面);如何在R中的單個圖上用不同的顏色繪製多條線?

例如

Species Count Transect 
Cod  25 1 
Cod  36 2 
Cod  45 3 
Haddock 12 1 
Haddock 23 2 
Haddock 34 3 

等等... 我可能有很多種類的,我想在一個圖繪製,所以我試圖用一個循環(我第一次去的正確嘗試使用循環!!)到加快這和做了以下

xrange <- range(Data$Transect) 
ymax <- max(Data$Count) 
plot(xrange,y=c(0,ymax+10), yaxs = "i", type="n", las=1, xlab="Transect  Number", ylab="Total Number") 
for (i in Data$Species){ 
species <- subset(Data, Species==i) 
lines(species$Transect, species$Count, type="o",lwd=2,lty=1,pch=NA)} 

這將產生一個陰謀與數據與一個單獨的行設置所有的物種,但我想這些線有一個獨特的顏色和我在努力做到這一點。

我已經嘗試了以下,但它不起作用,所有的行仍然出來作爲相同的顏色,我不知道接下來要嘗試什麼?

nspecies <- levels(Data$Species) 
colors<- rainbow(nspecies) 
for (i in Data$Species) { 
species <- subset(Trial, Species==i) 
lines(species$Haul, species$Catch, type="o",lwd=2,lty=1,pch=NA, col=colors[i])} 

任何幫助將是巨大的感謝!

+2

歡迎堆棧溢出!看看ggplot2 http://stackoverflow.com/questions/6364081/plot-lines-in-different-layers-ggplot2?rq=1 – Iris

回答

0

簡短的回答是看看ggplot2,因爲這遠遠勝過使用情節。 剛看到上面的工作,這裏的工作示例(代碼稍作修改):

tt <- "Species Count Transect 
Cod  25 1 
Cod  36 2 
Cod  45 3 
Haddock 12 1 
Haddock 23 2 
Haddock 34 3" 

Data <- read.table(text=tt,header = T) 
xrange <- range(Data$Transect) 
ymax <- max(Data$Count) 

my.levels <- levels(Data$Species) 
my.colors<- rainbow(length(my.levels)) 

plot(xrange, 
    y=c(0,ymax+10), 
    yaxs = "i", 
    type="n", 
    las=1, 
    xlab="Transect Number", 
    ylab="Total Number") 

for (i in 1:length(my.levels)) 
{ 
    species <- subset(Data, Species==my.levels[i]) 
    lines(species$Transect, species$Count, type="o",lwd=2,lty=1,pch=NA, col = my.colors[i]) 
} 

在執行時將繪製:

enter image description here

+0

非常感謝,需要開始習慣使用ggplot,但我明白什麼是現在我的代碼出錯了!謝謝 –

+0

一定要檢查http://rweb.stat.ucla.edu/ggplot2 - 非常互動/信息。 – rbm

0

的問題是,隨着每次調用lines(),你正在使用相同的顏色。爲了防止這種情況發生,每次調用lines()時,都需要迭代一個顏色矢量。請注意,由於您正在遍歷Data$Species,因此您實際上在此覆蓋了三行,您可能打算使用unique(Data$Species)

但按@虹膜的評論,你可以這樣做更容易使用ggplot2

require(ggplot2) 
ggplot(data = Data, aes(x = Transect, y = Count, group = Species)) + 
    xlab("Transect Number") + ylab("Total Number") + 
    geom_line(aes(color = Species)) 
相關問題