在 R 中,颜色根据变量映射的堆叠条形图

In R stacked barplot with colors mapped according to variable

我刚开始使用 R,而且我被困在条形图上。 我想制作一个堆叠条形图,其中根据变量选择颜色。

我的数据是这样的:

厚度
点3点5点6点7点8点9点11
第一层 25 20 90 80 100 45 75
层 2 5 20 0 0 0 70 0
层 3 80 5 0 0 0 0 0

类型
点3点5点6点7点8点9点11
第一层 4 3 3 3 3 3
层 2 5 5 6 6 6 5 6
层 3 4 3 6 6 6 6 6

对于每个点,有一些厚度 AL 需要堆叠在一起,类型 AL_col 表示堆叠条需要具有的颜色。

我的脚本:

col1<-c("green","brown","purple","black","yellow", "white")
barplot(Thickness, col=col1[Type])

谢谢!

编辑

我会试着解释得更好一点: 我有 10.000 个位置,这些是点(例如上面的点 3、5、6、7、8、9、11) 这些位置可以由 3 层组成。 这些层的厚度和 material 的类型不同。 我想做的是: 每个点都有一个堆叠的条形图,其中可以看到每一层的厚度。 要查看 material 的类型,我想使用配色方案。每个点都不同。

而不是基础 R 图形,也许使用 ggplot

library(ggplot)

AL <- data.frame(point = c(3, 5, 6, 7, 8, 9, 11), layer1 = c(1, 25, 20, 90, 80, 100, 45),
                 layer2 = c(5, 20, 0, 0, 0, 70, 0), layer3 = c(80, 5, 0, 0, 0, 0, 0))
AL.m <- melt(AL, id.vars = "point")

col1<-c("green","brown","purple","black","yellow", "white")
barplot(AL, col=col1[AL_col])

ggplot(AL.m, aes(x = point, y = value, fill = variable)) + geom_bar(stat = "identity", position = "stack") +
  scale_fill_manual(values = col1)

评论后编辑 由于只有三层,所以只使用了 col1 的前三种颜色。 我不清楚您要寻找的替代配色方案。

标准条形图也可以,您只需将数据放入矩阵即可。示例:

    L <- data.frame(point = c(3, 5, 6, 7, 8, 9, 11), 
    layer1 = c(1, 25, 20, 90, 80, 100, 45),                  
    layer2 = c(5, 20, 0, 0, 0, 70, 0), 
    layer3 = c(80, 5, 0, 0, 0, 0, 0))

    barplot(t(as.matrix(L)),col=c("blue","black","yellow","orange"))

做你想做的事意味着循环:

    L <- data.frame(
            layer1 = c(25, 20, 90, 80, 100, 45),     
            layer2 = c(5, 20, 0, 0, 70, 0), 
            layer3 = c(80, 5, 0, 0, 0, 0))
    rownames(L)<-c(3, 5, 6, 7, 8, 9)

    AL_col <- matrix(c(
                4,3,3,3,3,3,
                5,5,6,6,6,5,
                4,3,6,6,6,6),ncol=6,byrow=TRUE)
    colnames(AL_col) <- c("point3","point5","point6","point7","point8","point9")
    rownames(AL_col) <- c("layer1","layer2","layer3")

    col1<-c("green","brown","purple","black","yellow", "white","blue")

    # the problem is then to make polygons corresponding to your colors

    maxHeight <- max(as.matrix(L) %*% rep(1,dim(L)[2]))
    widthPol <- 0.5
    plot(c(1-widthPol,dim(L)[1]+widthPol),c(0,maxHeight),type="n",xlab="Points",ylab="Height")

    for(iPoint in 1:6){
        currentY <- 0
        for(iLayer in 1:3){
            addedY <- L[iPoint,iLayer]
                if(addedY>0){
                    xs <- c(rep(iPoint-widthPol/2,2),rep(iPoint+widthPol/2,2))
                        ys <- c(0,addedY,addedY,0)
                        colPoly <- col1[AL_col[iLayer,iPoint]]
                        polygon(x=xs,y=ys+currentY,col=colPoly)
                        currentY <- currentY + addedY
                }
        }
    }