2015-09-20 103 views
1

我目前正在嘗試在R中的矩陣中繪製多列。到目前爲止,我已經計算出了一些東西,但這是我的問題 - 當我提交包含5列的矩陣時, 4行圖。我注意到,缺失的線總是最靠近x軸的線。我已經在這裏工作了好幾個小時,而且我嘗試了幾個不同的事情。我們將不勝感激任何關於如何讓R產生第5條線(相應的顏色填充X軸和線之間的空間)的建議或幫助。在R中繪製多個變量

gender=cbind(matrix(malepop),matrix(femalepop)) 
    plotmat(year,gender) 
    #a sample set 
    biggen=cbind(malepop,femalepop,malepop,femalepop) 
    #start of the function 
    plotmat2=function(years,m,colors){ 
     n=m/1000000 
     #create a plot with the base line 
     plot(years,n[,1],type='l',ylim=c(0,10)) 
     ##create a for loop to generate all other lines and fill in the spaces 
     for (i in ncol(n):2) { 
     newpop=matrix(rowSums(n[,1:i])) 
     lines(year,newpop) 
     cord.xmat=c(min(years),years,max(years)) 
     cord.ymat=c(-1,newpop[,1],-1) 
     polygon(cord.xmat,cord.ymat,col=clrs[i]) 
     next 
     cord.xmat=c(min(years),years,max(years)) 
     cord.ymat1=c(-1,n[,1]/1000000,-1) 
     polygon(cord.xmat,cord.ymat,col="purple") 
     } 
    } 
    #sample color set 
    clrs=c("red","blue","yellow","pink","purple", "cyan", "hotpink") 
    #run the function 
    plotmat2(year,biggen,clrs) 

This is what I'm getting currently (the blue space should have another line somewhere in the midst of it which has the color red filling between that line and the x-axis

感謝您的任何和所有幫助您可以提供!

回答

1

這可能是因爲您無意中用其他彩色部分遮蓋了第一行,並且您可能正在跳過爲n [,1]創建多邊形。

從你試圖按降序排列圖表的方式,我假設你知道你的列是按升序排列(在你的示例圖中粉色部分是矩陣中的最後一列「biggen 「)。如果我對此有誤,可以使用密度參數更改多邊形陰影,這可能會幫助您瞭解是否意外遮蓋了其他部分。

## plotmat2 function 
plotmat2=function(years,m,colors){ 
     n=m/1000000 

     #create a blank plot based on the baseline 
     plot(years,n[,1],type='n',ylim=c(0,10)) 

     ##create a for loop to generate all other lines and fill in the spaces 
     for (i in ncol(n):1) { 
     newpop=matrix(rowSums(n[,1:i])) 
     lines(year,newpop) 
     cord.xmat=c(min(years),years,max(years)) 
     cord.ymat=c(-1,newpop[,1],-1) 
     polygon(cord.xmat,cord.ymat,col=colors[i], density=10) 
     } 
} 

P.S.如果這不能解決問題,那麼如果您提供了一部分數據集可能會有所幫助。我仍然在學習關於R和關於StackOverflow的內容,但是這似乎是在我閱讀的很多線程上給出的合理建議。祝你好運!