用组和比例确定填充渐变的矩形

我正在尝试绘制一堆矩形,填充是按比例确定的颜色渐变。

首先,我有一个像这样的数据框:

SELECT TS,TO_TIMESTAMP_TZ(ROUND(EXTRact(EPOCH_SECOND FROM TS)/(10*60))*(10*60)) RTS
FROM (SELECT TIMESTAMP_TZ_FROM_PARTS(2020,3,29,1,59,'Europe/Oslo') TS);

=> 2020-03-29 01:59:59.000 +0100      2020-03-29 03:00:00.000 +0200

其中整数对应于我进行的100次分析的组分配。我希望具有混合组分配的样本具有颜色渐变(例如,sample4为25%蓝色和75%红色)。

这是我的代码:

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

这是我当前的输出:

Rectangle Gradient Plot

但是,颜色> 1的矩形显示为50/50,这不是正确的比例。例如,顶部附近的紫色和浅蓝色实际上应该分别为88%和12%。

我被困在这里。有谁知道一种按比例绘制颜色填充的方法?

非常感谢您的宝贵时间。

clshz2009 回答:用组和比例确定填充渐变的矩形

好,所以这更多是gradient.rect()函数的问题。它根本不是为您想要的。无论如何,它将始终产生均等的矩形。

但是,这并不意味着您无法绘制情节。您只需要使用good'ol rect()函数并自己计算拆分。

我做了我可以从您的帖子中得到的伪数据...

df <- "sampleID,1,2,3,4,5
sample1,1
sample2,1
sample3,2
sample4,2
sample5,2
sample6,2
sample7,2"
df <- read.table(text = df,h = T,sep = ",",row.names = 1)

这一切都没有改变:

col2rownames <- function(df){
  rownames(df) <- df$sampleID
  df$sampleID <- NULL
  return(df)
}
df <- col2rownames(df)
df.freq <- apply(df,table)
df.freq <- lapply(df.freq,function(x) { as.data.frame(x,stringsAsFactors = F) } )
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
)
collist <- list()
collist <- lapply(df.freq,function(x) { 
  colors[x[,1]]
})
collist <- lapply(collist,as.vector)
mylen <- length(df.freq)

这是新东西:

# Plot an empty box
plot(c(0,1),c(0,mylen),type="n",axes=F)

# Initialize counter (you don't really need 2 for this...)
counter <- 0

# Plot rectangles of given colors,split by given freqs
rect_split <- function(freqs,colors,ybot,ytop,xleft = 0,xright = 1,...){
  freqs <- freqs/sum(freqs) # norm to 1
  xpos <- c(0,cumsum(freqs)) # get splits for colors
  xpos <- (xpos - xleft)/(xright - xleft) # scale between xleft and xright
  sapply(seq_along(freqs),function(i){
    rect(xleft = xpos[i],xright = xpos[i+1],ybottom = ybot,ytop = ytop,col = colors[i],...)
  })
}

for (i in 1:length(collist)){ 
  cols <- c(collist[[i]])
  freqs <- df.freq[[i]][,2] # assuming the freqs are in the order of the colors

  rect_split(freqs,cols,ybot = counter,ytop = counter + 1)
  counter <- counter + 1
}

此图:

enter image description here

本文链接:https://www.f2er.com/2980186.html

大家都在问