我有一个矩阵,显示我用于某些线性组合的变量的分类值和相应的r.squared值。由于用于线性组合的变量数在1到4之间变化,因此有几个NA。
我使用ggplot2来获取此输出,这非常接近我想要的: Rplot1.png
但是,我不希望显示NAs,我无法弄清楚如何执行此操作geom_text()
正在显示所有内容,或者如果我尝试geom_text(aes(label = sprintf("%1.0f",value[!is.na(value])))
之类的内容而给我一个错误,因为在这种情况下,长度是错误的。
此外,我希望最后一列使用不同的精度(2位小数)和不同的颜色代码进行格式化。
我的数据:
col1 <- c(3, 12, 12, 4, 2, 4, 6, 4, 15, 13, 1, 4, 13, 13, 4, 4, 6, 13, 1, 4)
col2 <- c(14, 29, 33, NA, 3, 14, 14, NA, 18, 18, 3, NA, 18, 18, 5, NA, 14, 18, 3, NA)
col3 <- c(22, 33, NA, NA, 6, 23, NA, NA, 25, 25, NA, NA, 24, 25, NA, NA, 21, 25, NA, NA)
col4 <- c(25, NA, NA, NA, 9, NA, NA, NA, 31, NA, NA, NA, 25, NA, NA, NA, 27, NA, NA, NA)
col5 <- c(0.99879174731700204326, 0.99026853951234095064, 0.97577109510739901133, 0.94129388844778405510, 0.99280352772128999117, 0.96836063265002103595, 0.93791976583184200056,
0.84138009684215697703, 0.98856063354420098399, 0.97136223282556599656, 0.79804189507803902082, 0.64147943288862196987, 0.99825754796980703532, 0.96893762747413503256,
0.87923096638698294836, 0.78073080902317304464, 0.99370888114350197640, 0.95233511051330899111, 0.80470423703937299376, 0.62955867989309499677)
plotMat2 <- data.frame(cbind(col1,col2,col3,col4,col5),
row.names=c("data.max4","data.max3","data.max2","data.max1","data.3QT4","data.3QT3","data.3QT2","data.3QT1","data.median4","data.median3","data.median2",
"data.median1","data.mean4","data.mean3","data.mean2","data.mean1","data.1QT4","data.1QT3","data.1QT2","data.1QT1"))
names(plotMat2) <- c("SU" , "SU.1", "SU.2", "SU.3", "rsq" )
我的代码:
library(reshape)
cor_dat2 <- melt(as.matrix(plotMat2))
names(cor_dat2) <- c('Var1','Var2','value')
cor_dat2$Var1 <- factor(row.names(plotMat2), levels=rev(row.names(plotMat2)))
cor_dat2$Var2 <- factor(cor_dat2$Var2, levels=colnames(plotMat2))
library(ggplot2)
p <- ggplot(data = cor_dat2, aes(x = Var2, y = Var1)) +
geom_tile(aes(fill = value), colour = "black") +
geom_text(aes(label = sprintf("%1.0f",value))) +
scale_fill_gradient(low = "white", high = "red")
print(p)
感谢任何帮助, 提前致谢, 埃里克
答案 0 :(得分:7)
只需将geom_text
替换为:
geom_text(aes(label = ifelse(is.na(value), "", sprintf("%1.0f",value)))) +