-2

我刚从 R 开始,我被困在 barplots 上。我想制作一个堆叠的条形图,其中颜色是基于变量选择的。

我的数据看起来像这样:

厚度
点 3 点 5 点 6 点 7 点 8 点 9 点 11
layer1 25 20 90 80 100 45 75
layer2 5 20 0 0 0 70 0
layer3 80 5 0 0 0 0 0

类型
点 3 点 5 点 6 点 7 点 8 点 9 点 11
layer1 4 3 3 3 3 3 3
layer2 5 5 6 6 6 5 6
layer3 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 层组成。这些层的厚度和材料类型不同。我想做的是:每个点都有一个堆叠的条形图,可以看到每层的厚度。并查看我想使用配色方案的材料类型。每个点都不同。

4

2 回答 2

1

而不是基本的 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)

在此处输入图像描述

COMMENT 后编辑 由于只有三层,所以只使用 col1 的前三种颜色。我不清楚您正在寻找什么替代配色方案。

于 2015-02-24T13:30:02.573 回答
1

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

    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
                }
        }
    }

在此处输入图像描述

于 2015-02-24T14:12:56.167 回答