如何使用ggplot2绘制概率热图?

时间:2017-11-01 17:12:51

标签: r plot ggplot2 tidyverse

我说每行都有一堆带有x和y坐标以及TRUE / FALSE的数据:

library(tidyverse)
set.seed(666) #666 for the devil
x <- rnorm(1000, 50, 10)
y <- sample(1:100, 1000, replace = T)
result <- sample(c(T, F), 1000, prob = c(1, 9),replace = T)
data <- tibble(x, y, result)

现在,我想制作一个图表,根据该数据显示某个区域为TRUE的可能性。我可以将数据分组为小方块(或其他)并计算TRUE百分比然后绘制,但我想知道ggplot2中是否有某些东西会自动为我做这些。

3 个答案:

答案 0 :(得分:0)

不完全在ggplot2中,但以下内容会产生我认为您要求的内容

library(tidyverse)
library(broom)
set.seed(666) #666 for the devil

data.frame(x = rnorm(1000, 50, 10), 
           y = sample(1:100, 1000, replace = T), 
           result = sample(c(T, F), 1000, prob = c(1, 9), replace = T)) %>% 
  do(augment(glm(result ~ x * y, data = ., family = "binomial"), type.predict = "response")) %>% 
  ggplot(aes(x, y, color = .fitted)) + 
  geom_point()

geom_hex代替geom_point看起来很有趣

答案 1 :(得分:0)

ggplot(data, aes(x = x, y = y, z = as.numeric(result))) +
    stat_summary_2d(bins = 20, color = "grey", fun = mean) +        
    theme_classic()

enter image description here

答案 2 :(得分:0)

这似乎是另一种解决方案:

library(tidyverse)

#Preparing data
set.seed(666) #666 for the devil
data <- tibble(x = rnorm(1000, 50, 10),
               y = sample(1:100, 1000, replace = T),
               result = sample(c(T, F), 1000, 
                               prob = c(1, 9), replace = T)) %>%
filter(result == TRUE)

#Plotting with ggplot
ggplot(data, aes(x, y)) +
geom_bin2d()

Result geom_bin2d