我刚从R开始,我被困在了条形码上。 我想制作一个堆积的条形图,其中颜色是根据变量选择的。
我的数据看起来像这样:
厚度
点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层组成。 这些层的厚度和材料类型不同。 我想要做的是: 对于每个点都有一个堆叠的条形图,其中可以看到每层的厚度。 并且要查看我想要使用颜色方案的材料类型。每个点都有所不同。
答案 0 :(得分:1)
可能使用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的前三种颜色。 我不清楚你正在寻找什么替代着色方案。
答案 1 :(得分:0)
标准条形图也很好,你只需要将数据放在矩阵中。示例:
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
}
}
}