【发布时间】:2019-12-04 07:12:28
【问题描述】:
我正在尝试绘制一堆矩形,填充是由比例确定的颜色渐变。
首先,我有一个这样的数据框:
sampleID 1 2 3 4 5 ... 100
sample1 1 1 1 1 1 ... 1
sample2 1 1 1 1 1 ... 1
sample3 2 2 2 2 2 ... 2
sample4 2 2 1 1 2 ... 2
...
其中整数对应于我进行的 100 次分析的组分配。我希望具有混合组分配的样本具有颜色渐变(例如,sample4 是 25% 的蓝色和 75% 的红色)。
这是我的代码:
library("RColorBrewer")
library("plotrix")
# Make sampleID column rownames and remove from df
col2rownames <- function(df){
rownames(df) <- df$sampleID
df$sampleID <- NULL
return(df)
}
df <- col2rownames(df)
# Get a list of frequency tables corresponding to each row in df.
df.freq <- apply(df, 1, table)
# Convert list of table() objects to list of data.frames
df.freq <- lapply(df.freq, function(x) { as.data.frame(x, stringsAsFactors = F) } )
# Make color vector
colors <- c(
"1" = "#808080", # BXCH
"2" = "purple4", # BXON
"3" = "yellow3", # BXFL
"4" = "orange1", # BXEA
"5" = "mediumaquamarine", # BXFL second cluster
"6" = "magenta3", # GUFL
"7" = "blue", # GUMS
"8" = "red", # BXMX
"9" = "green2", # BXTT
"10" = "#00ffff" # BXDS
)
# Subset only colors present in each df.freq data.frame
collist <- list()
collist <- lapply(df.freq, function(x) {
colors[x[, 1]]
})
# Convert to list of vectors
collist <- lapply(collist, as.vector)
# Get number of data frames in list
mylen <- length(df.freq)
# Plot an empty box
plot(1:mylen, type="n", axes=F)
# Initialize counters
counter_min <- 0
counter_max <- 1
# Initialize newcollist
newcollist <- list()
# Plot rectangles with color gradient
for (i in 1:length(collist)){
colsubset <- c(collist[[i]])
newcollist[[i]] <- colsubset
gradient.rect(xleft = 0, ybottom = counter_min, xright = 5, ytop = counter_max, col = colsubset, gradient = "x")
counter_min <- counter_max
counter_max <- counter_min + 1
}
这是我当前的输出:
但是,颜色 >1 的矩形显示为 50/50,这不是正确的比例。例如,靠近顶部的紫色和浅蓝色实际上应该分别为 88% 和 12%。
我被困在这里。有谁知道按比例绘制颜色填充的方法?
非常感谢您的宝贵时间。
【问题讨论】:
-
您好,欢迎来到 SO !如果您提供可重复的示例,人们可以更轻松地帮助您。请在您的问题中添加一些数据。如果太大,可以使用
dput(my_data)或dput(head(my_data))。 -
我很抱歉。下次我将添加更好的可重现数据。但是,您在下面完全解决了我的问题。谢谢!
标签: r plot percentage rectangles plotrix