2016-07-05 84 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)