更改的酒吧颜色barplot相对于钢筋长度

问题描述 投票:1回答:2

我已经绘制在基础R堆叠barplot:

set.seed(12)
dat <- matrix(sample(1:6, 6) , nrow = 3)
rownames(dat) <- c("A", "B", "C")
colnames(dat) <- c("blue", "green")
barplot(dat, beside = TRUE)

我想

  • 一种颜色分配给每个组的杆和
  • 改变亮度取决于杆的长度(黑色),使得长度为6的杆具有全彩色。

像这样:

enter image description here

我怎样才能做到这一点?


我已经适应@按以下方式NYA的回答:

set.seed(12)
dat <- matrix(sample(1:6, 6) , nrow = 3)
rownames(dat) <- c("A", "B", "C")
colnames(dat) <- c("blue", "green")

sequence <- seq(1, 6, 1)  # min = 1, max = 6, steps = 1
resolution <- length(sequence)
blues <- colorRampPalette(c("black", "blue"))(resolution)
greens <- colorRampPalette(c("black", "green"))(resolution)

cols <- c(blues[match(dat[, "blue"], sequence)],
          greens[match(dat[, "green"], sequence)])

mar.default <- c(5,4,4,2) + 0.1
par(mar = mar.default + c(2, 0, -2, 0))
barplot(dat, beside = TRUE, col = cols)

enter image description here

r colors bar-chart
2个回答
1
投票

首先,我们需要为绘制创建颜色渐变。让我们用从黑10个色的分辨率要么蓝色或绿色。

res <- 10
blues <- colorRampPalette(c("black", "blue"))(res)
greens <- colorRampPalette(c("black", "green"))(res)

其次,我们将使用功能cut裹挟的因素来确定梯度值适合在那里。我们将使用哪个颜色对应于该数据值的因素(子集划分的行当在R解释为数字)来选择。

b.cut <- as.factor(cut(dat[, "blue"], breaks = res))
g.cut <- as.factor(cut(dat[, "green"], breaks = res))
cols <- c(blues[b.cut], greens[g.cut])
cols

这些颜色可用于绘制。请注意,我改变了你的输入数据的名称,因为data是一个功能和良好的编程习惯是避免与变量覆盖功能。

barplot(dat, beside = TRUE, col = cols)

enter image description here


0
投票

您可以通过添加颜色参数为col包括代码颜色选项修改最后一行。我修改最后一行由下面给出添加的颜色的适当的六角形代码:

barplot(data, beside = TRUE,col=c("#0000FF","#0066FF","#00FFFF","#ADFF2F","#008000","#006400"))

这是我得到的情节。

修改后的代码如下公布。根据你的愿望改变六角颜色代码。我提到Color Cycling in R部分从datamentor网站。

set.seed(12)
data = matrix(sample(1:6, 6) , nrow = 3)
rownames(data) = c("A", "B", "C")
colnames(data) = c("blue", "green")
barplot(data, beside = TRUE,col=c("#0000FF","#0066FF","#00FFFF","#ADFF2F","#008000","#006400"))
© www.soinside.com 2019 - 2024. All rights reserved.