[英]R change the colour of bar in a stacked barplot
Here is a barplot that I constructed: 这是我构建的一个条形图:
data<-read.table(text="Unsuit lsuit imp
164 124 480
115 28 31
55 165 9
",header=T)
barplot(as.matrix(data))
It is a stacked barplot, each bar has three sub-bar (bottom, middle and the top)(sorry for the use of wrong jargon) 它是一个堆叠的条形图,每个条形有三个子条(底部,中间和顶部)(抱歉使用错误的行话)
What I want to do is: 我想做的是:
1) give the bottom sub-bar in Unsuit
(corresponding to the value 164), middle sub-bar in lsuit
(28) and top sub-bar in imp
(9) the same colour (brown) 1)将“不Unsuit
的底部子栏(对应于值164),不lsuit
(28)中的中间子栏和imp
(9)中的顶部子栏lsuit
相同的颜色(棕色)
2) middle sub-bar Unsuit
(115), bottom sub-bar in lsuit
and middle sub-bar in imp
same colour (red) 2)中间子栏Unsuit
(115),在底部子栏lsuit
和在中间子栏imp
相同的颜色(红色)
3) top sub-bar in Unsuit
(55), top sub-bar in 'lsuit (165) and bottom sub-bar in
imp`(480) the same colour (green) 3) Unsuit
(55)中的顶部子栏,lsuit (165) and bottom sub-bar in
imp`(480)中的(165) and bottom sub-bar in
使用相同的颜色(绿色)
and then show the colour of sub-bar in a legend 然后在图例中显示子栏的颜色
Would really appreciate on advise how to do this in R. I do not want to change the order of the bar which is important for me. 非常感谢建议如何在R中这样做。我不想改变对我来说重要的酒吧顺序。
Thanks 谢谢
I think the only way is to draw rectangles by hand. 我认为唯一的方法是手工绘制矩形。 Here's a possible function (pretty generic, it takes a matrix of values and a matrix of corresponding colors) that should give your desired result : 这是一个可能的函数(相当通用,它需要一个值矩阵和一个对应颜色的矩阵),应该可以提供您想要的结果:
# custom function
customBarPlot <- function(valueMatrix,colorMatrix,main=NULL){
stopifnot(all(dim(valueMatrix) == dim(colorMatrix)))
maxVal <- max(apply(valueMatrix,2,cumsum))
# draw an empty plot
plot(0,type='n',xlim=c(0,1),ylim=c(0,maxVal),main = main,xlab=NA,ylab=NA,axes=FALSE)
nCols <- ncol(valueMatrix)
space <- 0.03 # 3% of the space between bars
barWidth <- (1.0 - nCols * space + space) / nCols
# add the rectangles
for(col in 1:nCols){
centerOfRect <- col * (space + barWidth) - barWidth / 2
centers <- rep.int(centerOfRect,nCols)
rect(xleft=centers - barWidth / 2,
xright=centers + barWidth / 2,
ybottom=c(0,head(cumsum(valueMatrix[,col]),-1)),
ytop=cumsum(valueMatrix[,col]),
col=colorMatrix[,col])
}
# add axis
axis(1,at=1:nCols * (space + barWidth) - barWidth / 2, labels=colnames(valueMatrix),tick=FALSE)
axis(2)
invisible()
}
# let's call the function
data<-read.table(text="Unsuit lsuit imp
164 124 480
115 28 31
55 165 9
",header=T)
customBarPlot(valueMatrix=as.matrix(data),
colorMatrix=rbind(c('Brown','Red','Green'),
c('Red','Brown','Red'),
c('Green','Green','Brown')))
Result: 结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.