堆积条形图中每个条形的不同颜色 - 基本图形学

15

我想绘制一个类似于附件的堆叠条形图,但我希望颜色在类别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
非常感谢任何建议。

示例图表


plotrix 包中的 barp() 函数允许将矩阵传递给 col - 但它只能绘制 分组 条形图,而不是 堆叠 的。你可能需要自己编写函数(可能需要大量调用 rect() 函数)。如果你这样做了,请在这里发布,我会很高兴为你点赞。 - Stephan Kolassa
那个解决方案在这里提到了:https://stat.ethz.ch/pipermail/r-help/2007-March/126848.html。但是下面的解决方案更适合我,因为我每个条形图只需要一种颜色。 - Martin
3个回答

8
一种解决方法:扩展您的矩阵,使值对应于虚构类别,每个类别只有一种颜色。在这些类别中,只有一个会实际包含数据,即aabbcc中的一个。
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


8
这是通过逐个添加彩色条形图来实现的:
# 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


这是一个非常简洁的解决方案,只使用了一个颜色向量和简单的 fill = col。这种方法适用于任何 ggplot 吗?(我想知道您是如何知道绘图将使用颜色的顺序的?) - stevec
1
这是非常老的代码,我认为应该有更好的方法来构建col向量。关于ggplot,它确实是设计用于长格式(或整洁格式),因此它总是“偏爱”一列。Hadely根据这个理论设计了它 https://vita.had.co.nz/papers/tidy-data.pdf - David Arenburg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接