简体   繁体   English

使用barplot()在R中按组对堆叠的条形图进行颜色编码

[英]Color coding stacked barplots by groups in R using barplot()

My goal is to create a stacked barplot in R from a matrix, where each column in the matrix is a bar with a different color, and each bar represents the sum of all rows in the column. 我的目标是根据矩阵在R中创建一个堆叠的条形图,其中矩阵中的每一列都是具有不同颜色的条形,每个条形代表该列中所有行的总和。

Here's dummy data and bar plot scripts I'm using to trouble shoot: 这是我用来排除故障的虚拟数据和条形图脚本:

m = matrix(1:9, ncol = 3, byrow = TRUE)
v = matrix(c("red", "blue", "green"), ncol=3, nrow=3, byrow=TRUE)
m #matrix of values
v #matrix of colors for each point

If I only plot row 1, colors are assigned correctly 如果仅绘制第1行,则颜色分配正确

barplot(m[1,], col=v[1,])

If I plot rows 1-3 w/o designating colors, data is stacked correctly: 如果我绘制1-3行而不指定颜色,则数据正确堆叠:

barplot(m[c(1:3),])

If I plot rows 1-3 with BESIDE=TRUE, color codes correctly (but obviously is not stacked) 如果我用BESIDE = TRUE绘制第1-3行,则颜色代码正确(但显然没有堆叠)

barplot(m[c(1:3),], col=v[c(1:3),], beside = TRUE)

If I attempt to plot rows 1-3, data stacks correctly, but color coding is not applied as needed: 如果我尝试绘制第1-3行,则数据可以正确堆叠,但是未根据需要应用颜色编码:

barplot(m[c(1:3),], col=v[c(1:3),])

Any suggestions? 有什么建议么?

Try this 尝试这个

v <- c("red","blue","green")
barplot(m, col=v, beside=FALSE)

Each row of your data matrix will take on a single color 数据矩阵的每一行将采用单一颜色

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM