如何从ggplot2中的热图中排除异常值?

时间:2017-11-30 12:22:06

标签: r ggplot2 visualization heatmap ggmap

嗨, 我想在地图上绘制每平方的平均转换率。这很好用。有问题的是只有很少记录的正方形通常达到接近0或1的极值。这使得图很难读。有没有办法如何排除未达到特定记录数的方块?或者设置颜色范围从例如0.3 - 0.7?


CODE:

library(ggplot2)
library(ggmap)
manila_map <- get_map("Manila,Philippines", zoom=11)

map <- ggmap(manila_map)
map + stat_summary_2d(
   geom = "tile", 
   data = data,
   fun = "mean",
   binwidth = 0.02,
   aes(x = lon, y = lat, z = requested),
   alpha = 0.4
) +
scale_fill_gradient2(low = "red", mid = "yellow", high = "#007f00", midpoint=0.5)

enter image description here

1 个答案:

答案 0 :(得分:3)

首先,将数据集中的离群值更改为NA

data$requested <- ifelse(data$requested <= 0.7 & data$requested >= 0.3, 
                         data$requested, NA)

然后,在na.value中添加scale_fill_gradient(),使NA值为中性色

scale_fill_gradient2(low = "red", mid = "yellow", high = "#007f00", midpoint=0.5, 
                     na.value = "grey50")