different colors for each bar in stacked bar graph - base graphics

偶尔善良 提交于 2019-11-29 04:07:03

A workaround: extend your matrix so that values correspond to fictitious categories, with just one color per category. Only one of aa, bb and cc will actually have data in those categories.

> 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

And plot as you did:

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

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)

This works by adding one coloured bar to the plot at a time:

# 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) 
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!