我正在使用ggplot2来生成热图,但是NA值会使热图成为一种颜色。
示例数据框:
id<-as.factor(c(1:5))
year<-as.factor(c("Y13", "Y14", "Y15"))
freq<-c(26, 137, 166, 194, 126, 8, 4, 76, 20, 92, 4, NA, 6, 6, 17)
test<-data.frame(id, year, freq)
test
id year freq
1 Y13 26
2 Y14 137
3 Y15 166
4 Y13 194
5 Y14 126
1 Y15 8
2 Y13 4
3 Y14 76
4 Y15 20
5 Y13 92
1 Y14 4
2 Y15 NA
3 Y13 6
4 Y14 6
5 Y15 17
我将以下内容用于热图:
# set color palette
jBuPuFun <- colorRampPalette(brewer.pal(n = 9, "RdBu"))
paletteSize <- 256
jBuPuPalette <- jBuPuFun(paletteSize)
# heatmap
ggplot(test, aes(x = year, y = id, fill = freq)) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +
geom_tile() +
scale_fill_gradient2(low = jBuPuPalette[1],
mid = jBuPuPalette[paletteSize/2],
high = jBuPuPalette[paletteSize],
midpoint = (max(test$freq) + min(test$freq)) / 2,
name = "Number of Violations")
结果是整个热图上的灰色。
当我从数据框中删除“NA”时,热图会正确呈现。
我通过专门为“NA”值指定颜色来试验这一点(例如,通过
scale_fill_gradient2(low = jBuPuPalette[1],
mid = jBuPuPalette[paletteSize/2],
high = jBuPuPalette[paletteSize],
na.value="yellow",
midpoint = (max(test$freq) + min(test$freq)) / 2,
name = "Number of Violations")
但是,这只会使整个热图变黄。
我错过了一些明显的东西吗?任何建议都表示赞赏。
感谢。
答案 0 :(得分:1)
评论回答:
ggplot处理NAs很好,但如果向量包含任何min
,则max
和NA
的默认值将返回NA
。您只需在定义比例的中点时为这些设置na.rm = TRUE
:
midpoint = (max(test$freq, na.rm = TRUE ) + min(test$freq, na.rm = TRUE)) / 2,