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

标签 r bar-chart stacked stacked-chart

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

相关文章:

javascript - 堆积图 - AmChart - JavaScript

python - matplotlib 中的堆积面积图和日期

r - 在长数据帧的特定时间内对字符串变量进行计数然后求和

r - 如何计算大型数据集中每 10 个数字的众数(统计)

ios - 当用户点击图表时创建一个 MarkerView

r - ggplot2 两侧带有正标签的双向条形图

r - 计算每个主题的平均值并重复每个主题行的值

r - gganimate 中的 Ghost geom_text

r - 使用 facet_grid() 调整条形图的小数百分比

highcharts - 如何在 Highcharts 的柱形图中显示值为零的列?