2016-07-05 52 views
1

我有R中的以下代碼:條件着色中的R

dat <- as.matrix(read.table(text ="2011 2012 2013 2014 
      A -330.2165 500.53 730.75 -130.0941 
      R 2036.32 1155.91 345.81 218.0350", header=TRUE)) 

pts <- pretty(c(min(dat),max(dat))) 

barplot(dat, 
     ylim=c(min(pts),max(pts)), 
     col=c("mediumvioletred","midnightblue"),  
     legend.text=c("Appropriation","Receipts"), 
     args.legend = list(x="topleft", bty="n")) 

的問題是,所有的值應爲「暗紫」挪用(A),而所有收據值的(R)應該是「midnightblue」。相反,如果A值是負值,它們也會被着色爲「midnightblue」。

有誰知道如何解決這個問題?或者至少,爲每個點繪圖指定顏色?

我發現了許多關於條形圖着色的解決方案 - 但不是堆積的條形圖。這篇文章最接近這個:Conditional Barchart coloring with a vector in R,但仍然沒有解決我的問題。

回答

0

雖然不是完全滿意,你可以用一些額外的步驟做:

# get the size of first bar (blue) with positive second bar added on 
# first plot (blue) 
barplot(firstBar, 
     ylim=c(min(pts),max(pts)), 
     col="midnightblue") 
# add second plot (red) 
barplot(dat[1,], col="mediumvioletred", add=TRUE) 
# add legend 
legend(x="topright", legend=c("Receipts", "Appropriation"), 
     fill=c("midnightblue", "mediumvioletred"), bty="n") 

第二個步驟將在第二排的頂部的第一行。

作爲替代方案,可以使用旁= TRUE在具有相鄰條形曲線而不是堆疊的:

barplot(dat, 
     col=c("mediumvioletred", "midnightblue"),  
     legend.text=c("Appropriation","Receipts"), 
     args.legend = list(x="topleft", bty="n"), beside=TRUE)