我希望“相当杂乱无章”的帖子不是我对How to create a time series plot in the style of a horizontal stacked bar plot in r 的回答!没关系,没有冒犯。
该解决方案可以根据您的数据进行调整,如下所示:
## store data
df <- read.csv(text='Day,Location,Length,Amount\n1,4,3,1.1\n1,3,1,.32\n1,2,3,2.3\n1,1,3,1.1\n2,0,0,0\n3,3,3,1.8\n3,2,1,3.54\n3,1,3,1.1',header=T);
## extract bar segment lengths from Length and bar segment colors from a function of Amount, both stored in a logical matrix form
lengths <- xtabs(Length~Location+Day,df);
amounts <- xtabs(Amount~Location+Day,df);
colors <- matrix(colorRampPalette(c('lightblue','blue','black'))(1001)[amounts/max(amounts)*1000+1],nrow(amounts));
## transform lengths into an offset matrix to appease design limitation of barplot(). Note that colors will be flattened perfectly to accord with this offset matrix
lengthsOffset <- as.matrix(setNames(reshape(cbind(id=1:length(lengths),stack(as.data.frame(unclass(lengths)))),dir='w',timevar='ind')[-1],colnames(lengths)));
lengthsOffset[is.na(lengthsOffset)] <- 0;
## draw plot
barplot(lengthsOffset,col=colors,space=0,xlab='Day',ylab='Length');
备注
- 在您的问题中,您尝试使用
colrs <- colorRampPalette(c('lightblue','blue','black'))(1000)[z] 构建颜色向量,其中z 是转换为“每千”形式的8 个原始Amount 值。这有一个小缺陷,z 元素之一为零,这不是有效的索引值。这就是为什么你有 7 种颜色,而本来应该是 8 种颜色。我在代码中修复了这个问题,将每千分之一的值加 1 并生成 1001 种颜色。
- 还与生成颜色有关,而不是只生成 8 种颜色(即每个原始
Amount 值一种),我生成了一个完整的颜色矩阵以平行于 lengths 矩阵(您在代码中称为 tab )。这个颜色矩阵实际上可以直接用作传递给barplot() 的col 参数的颜色向量,因为在内部它被展平为一个向量(至少在概念上)并且将对应于我们将要的偏移条段长度将 height 参数传递给 barplot()(请参阅下一个注释)。
- 正如我在上述帖子中更详细描述的那样,此解决方案的关键是创建条形段长度的“偏移矩阵”,在相邻列中为零,以便可以为每个段分配不同的颜色。我从
lengths 矩阵将其创建为lengthsOffset。
- 请注意,可能有点违反直觉,
height 参数中较低的索引值由 barplot() 绘制为较低的段,反之亦然,这意味着当您在终端中打印该数据时,文本显示是垂直的与它在条形图中的显示方式相反。如果您想要相反的顺序,您可以垂直反转 lengthsOffset 矩阵和 colors 向量,但我的代码中没有这样做。
作为参考,这里是所有的数据结构:
df;
## Day Location Length Amount
## 1 1 4 3 1.10
## 2 1 3 1 0.32
## 3 1 2 3 2.30
## 4 1 1 3 1.10
## 5 2 0 0 0.00
## 6 3 3 3 1.80
## 7 3 2 1 3.54
## 8 3 1 3 1.10
lengths;
## Day
## Location 1 2 3
## 0 0 0 0
## 1 3 0 3
## 2 3 0 1
## 3 1 0 3
## 4 3 0 0
amounts;
## Day
## Location 1 2 3
## 0 0.00 0.00 0.00
## 1 1.10 0.00 1.10
## 2 2.30 0.00 3.54
## 3 0.32 0.00 1.80
## 4 1.10 0.00 0.00
colors;
## [,1] [,2] [,3]
## [1,] "#ADD8E6" "#ADD8E6" "#ADD8E6"
## [2,] "#4152F5" "#ADD8E6" "#4152F5"
## [3,] "#0000B3" "#ADD8E6" "#000000"
## [4,] "#8DB1EA" "#ADD8E6" "#0000FA"
## [5,] "#4152F5" "#ADD8E6" "#ADD8E6"
lengthsOffset;
## 1 2 3
## 1 0 0 0
## 2 3 0 0
## 3 3 0 0
## 4 1 0 0
## 5 3 0 0
## 6 0 0 0
## 7 0 0 0
## 8 0 0 0
## 9 0 0 0
## 10 0 0 0
## 11 0 0 0
## 12 0 0 3
## 13 0 0 1
## 14 0 0 3
## 15 0 0 0