在堆叠条形图中,每个条形图都有不同的颜色--基本图形。

问题描述 投票:13回答:3

我想绘制一个像附件一样的堆叠条形图,但我希望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

r bar-chart stacked stacked-chart
3个回答
7
投票

一个变通的办法是:扩展你的矩阵,使数值对应于虚构的类别,每个类别只有一种颜色。只有一个 aa, bbcc 实际上会有这些类别的数据。

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

并像你一样绘制。

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

enter image description here


7
投票

这样做的方法是每次在图上加一个彩色条。

# 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


5
投票
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)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.