[英]How to color bar plot with bars dependent on column names in R
我有兩個數據框和一個 function maxthree ,它以數據框和行名作為參數,並在行上繪制三個最大值(按降序排列)和三個最大值的列的名稱。
set.seed(0)
df <- data.frame(A=c(3,2,1,4,5),B=c(1,6,3,8,4),C=c(2,1,4,8,9), D=c(4,1,2,4,6))
row.names(df)<-c("R1","R2","R3","R4","R5")
df2 <- data.frame(E=c(2,5,6,1,4),F=c(2,4,2,5,1),G=c(5,6,2,7,3),H=c(8,2,7,4,1))
row.names(df2)<-c("R6","R7","R8","R9","R10")
print(df)
A B C D
R1 3 1 2 4
R2 2 6 1 1
R3 1 3 4 2
R4 4 8 8 4
R5 5 4 9 6
print(df2)
E F G H
R6 2 2 5 8
R7 5 4 6 2
R8 6 2 2 7
R9 1 5 7 4
R10 4 1 3 1
maxthree <- function(data, row) {
order<-as.matrix(data[row, order(unlist(data[row, ]), decreasing = TRUE)[1:3]])
barplot(order)
}
maxthree(df2, "R7")
我試圖讓 function maxthree根據它們所在的列對每個條進行不同的着色。 因此,例如,如果 df2 中的列按以下方式着色:E=green、F=red、G=yellow、H=blue,則前一個條形圖中的條形應該是黃色、綠色、紅色(即命令)。 我知道如何通過在 barplot() 中使用“col”在普通條 plot 中着色,但我不知道在這種情況下如何在條中着色,因為它取決於條 plot 和訂單上出現的列其中。
這是一種使用命名向量為不同行定義 colors 的方法:
col.colors <- c(E="green", F="red", G="yellow", H="blue")
maxthree <- function(data, row) {
order<-as.matrix(data[row, order(unlist(data[row, ]), decreasing = TRUE)[1:3]])
order.names <- colnames(order)
order.colors <- col.colors[order.names]
barplot(as.vector(order), names.arg = order.names, col = order.colors)
}
maxthree(df2, "R7")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.