2014-04-01 137 views
7

我想繪製一個附加的條形圖,但我希望顏色在類別aa,bb和cc之間有所不同。具體來說,我希望bb中的灰色塊爲紅色,cc中的灰色塊爲綠色。下面的代碼作爲一個簡單的例子,說明了什麼我已經嘗試:堆疊條形圖中每個條的不同顏色 - 基本圖形

aa=c(0.2,0.6,0.1,0.1) 
bb=c(0.4,0.5,0.05,0.05) 
cc=c(0.5,0.25,0.1,0.15) 
x=cbind(aa,bb,cc) 
x #the data 
aa bb cc 

[1,] 0.2 0.40 0.50 
[2,] 0.6 0.50 0.25 
[3,] 0.1 0.05 0.10 
[4,] 0.1 0.05 0.15 

默認行爲,所有的塊在每個類別

col=rep(c("white","grey"),2) 
col 
# [1] "white" "grey" "white" "grey" 

barplot(x,col=col) 

相同的顏色,但我想在bb灰色塊是紅色和cc灰色塊綠色

col=cbind(rep(c("white","grey"),2),rep(c("white","red"),2),rep(c("white","green"),2)) 
col 

[,1] [,2] [,3] 
[1,] "white" "white" "white" 
[2,] "grey" "red" "green" 
[3,] "white" "white" "white" 
[4,] "grey" "red" "green" 

barplot(x,col=col) #not working 

col=c(rep(c("white","grey"),2),rep(c("white","red"),2),rep(c("white","green"),2)) 
col 
[1] "white" "grey" "white" "grey" "white" "red" "white" "red" "white" "green" "white" "green" 

barplot(x,col=col) #not working either 

的任何建議非常感謝如此。

example graph

+0

'barp() ''plotrix'包中的''''可以將一個矩陣提供給'col'--但它只能組合*條形圖,而不是*堆疊*。你可能需要在這裏推出你自己的函數(可能會有很多調用'rect()')。如果你這樣做,請把它張貼在這裏,我會愉快地提高它。 –

+0

該解決方案在此處提供:https://stat.ethz.ch/pipermail/r-help/2007-March/126848.html。但下面的解決方案對我來說更直接,因爲我只需要每條一種顏色。 – Martin

回答

5

一種解決方法:擴展您的矩陣,使得值對應於虛構的類別,每個類別只是一種顏色。 aabbcc中只有一個實際上具有這些類別的數據。

> xx <- rep(0,4) 
> x <- matrix(c(aa,xx,xx,xx,bb,xx,xx,xx,cc),ncol=3) 
> x 
     [,1] [,2] [,3] 
[1,] 0.2 0.00 0.00 
[2,] 0.6 0.00 0.00 
[3,] 0.1 0.00 0.00 
[4,] 0.1 0.00 0.00 
[5,] 0.0 0.40 0.00 
[6,] 0.0 0.50 0.00 
[7,] 0.0 0.05 0.00 
[8,] 0.0 0.05 0.00 
[9,] 0.0 0.00 0.50 
[10,] 0.0 0.00 0.25 
[11,] 0.0 0.00 0.10 
[12,] 0.0 0.00 0.15 

和情節像你一樣:

> col <- c(rep(c("white","grey"),2),rep(c("white","red"),2),rep(c("white","green"),2)) 
> barplot(x,col=col) 

enter image description here

+0

很好的答案,謝謝! – Martin

4
library(ggplot2) 
library(reshape2) 
x <- data.frame(aa=c(0.2,0.6,0.1,0.1), 
       bb=c(0.4,0.5,0.05,0.05), 
       cc=c(0.5,0.25,0.1,0.15), 
       dd = 1:4) 
x <- melt(x, "dd") 
col=c(rep(c("white","grey"),2),rep(c("white","red"),2),rep(c("white","green"),2)) 
ggplot(x, aes(x = variable, y = value)) + geom_bar(stat = "identity", fill = col) 

enter image description here

+0

另一個很棒的答案,謝謝! – Martin

3

這是通過在每次添加一個顏色條的情節:

# white bars 
barplot(x, col='white', axes=F, axisnames=F, yaxp=c(0,1,2), las=1) 
cols=c('grey','red','green') 

# add coloured bars 
for (i in 1:ncol(x)){ 
    xx = x 
    xx[,-i] <- NA 
    colnames(xx)[-i] <- NA 
    barplot(xx,col=c('white',cols[i]), add=T, axes=F) 
} 

stacked plot

+0

第三次感謝! – Martin

相關問題