gpt4 book ai didi

r - 堆叠条形图中每个条形的不同颜色 - 基础图形

转载 作者:行者123 更新时间:2023-12-04 01:51:28 27 4
gpt4 key购买 nike

我想绘制一个堆积条形图,如所附的那个,但我希望颜色在类别 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

最佳答案

这是通过一次向绘图添加一个彩色条来实现的:

# 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

关于r - 堆叠条形图中每个条形的不同颜色 - 基础图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22781685/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com