堆叠条形图中每个条的颜色不同-基本图形 [英] different colors for each bar in stacked bar graph - base graphics

查看:574
本文介绍了堆叠条形图中每个条的颜色不同-基本图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制一个堆积的条形图,如所附的图,但我希望颜色在类别aa,bb和cc之间变化.具体来说,我希望bb中的灰色块为红色,而cc中的灰色块为绿色.下面的代码作为一个简单的示例,说明了我已经尝试过的内容:

I want to plot a stacked bar graph like the one attached, but I want the colors to vary between the categories aa, bb and cc. Specifically, I want the grey blocks in bb to be red and the grey blocks in cc to be green. The following code serves as a simple example and illustrates what I have already tried:

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

默认行为,所有类别中的所有块均具有相同的颜色

default behavior, all blocks have the same color in each categories

col=rep(c("white","grey"),2)
col
# [1] "white" "grey"  "white" "grey" 

barplot(x,col=col)

但是我希望bb中的灰色块为红色,而cc中的灰色块为绿色

but I want the grey blocks in bb to be red and the grey blocks in cc to be green

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

非常感谢您的任何建议.

Many thanks for any suggestions.

推荐答案

一种解决方法:扩展矩阵,使值对应于虚拟类别,每个类别仅一种颜色. aabbcc中只有一个实际上具有这些类别中的数据.

A workaround: extend your matrix so that values correspond to fictitious categories, with just one color per category. Only one of aa, bb and cc will actually have data in those categories.

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)

这篇关于堆叠条形图中每个条的颜色不同-基本图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆