R更改堆叠条形图中条形的颜色
以下是我构建的条形图:R更改堆叠条形图中条形的颜色,r,bar-chart,R,Bar Chart,以下是我构建的条形图: data<-read.table(text="Unsuit lsuit imp 164 124 480 115 28 31 55 165 9 ",header=T) barplot(as.matrix(data)) 数据我认为唯一的方法是手工绘制矩形。 下面是一个可能的函数(非常通用,它需要一个值矩阵和一个相应颜色矩阵),它应该给出您想要的结果: # custom function customBarPlot <- function(value
data<-read.table(text="Unsuit lsuit imp
164 124 480
115 28 31
55 165 9
",header=T)
barplot(as.matrix(data))
数据我认为唯一的方法是手工绘制矩形。
下面是一个可能的函数(非常通用,它需要一个值矩阵和一个相应颜色矩阵),它应该给出您想要的结果:
# 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')))
#自定义函数
customBarPlot我认为唯一的方法是手工绘制矩形。
下面是一个可能的函数(非常通用,它需要一个值矩阵和一个相应颜色矩阵),它应该给出您想要的结果:
# 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')))
#自定义函数
customBarPlot已编辑:抱歉,我复制了我的试错码而不是正确的版本编辑:抱歉,我复制了我的试错码而不是正确的版本