【问题标题】:Create a heatmap of ratio创建比率热图
【发布时间】:2022-11-10 23:10:11
【问题描述】:

每个人!我是 R 新手,想创建一个热图。 有一个包含列的数据集:

  • X: x 坐标
  • Y: y 坐标
  • Pet_type:宠物类型(猫、狗、仓鼠等)
  • Owner_type:所有者类型(成年男性、成年女性、儿童)

小数据集:

Owner Pet X Y
Male Dog 27.793 88.2128
Male Hamster 37.7177 87.9776
Female Cat 24.4547 87.3016
Kid Cat 36.464 84.9169
Kid Dog 29.4175 84.5433
Female Lizard 37.9588 83.9029
Male Guinea pig 44.8986 82.7822
Kid Dog 26.6216 82.0757
Male Hamster 46.2332 81.9817
Male Cat 31.9716 81.7507
Female Cat 22.8606 80.9761
Kid Dog 29.744 80.7988
Kid Lizard 32.2393 80.35
Female Guinea pig 38.92 78.8604
Male Dog 39.42 78.3604
Kid Hamster 32.2632 87.8267

创建一个热图的步骤是什么,它显示了一个特定宠物与该特定箱中所有宠物的比率? 例如:我想创建一个猫密度的热图,如果垃圾箱由 20 只宠物组成,其中 10 只是猫 - 垃圾箱的值为 0.5 或 50%,等等。

我正在使用 ggplot,并且我可以看到每个垃圾箱中的宠物总数。 在将其提供给 ggplot 之前,我应该对桌子进行哪些操作?

df %>% 
  ggplot(aes(X, Y))+
  geom_bin_2d(bins=15)

我正在努力理解如何创建一个声明,我想查看所有垃圾箱中的猫与所有宠物的比例。

所以,是的,如果有人可以帮助我解决这个问题,我将不胜感激(可能是一个简单的问题)

【问题讨论】:

  • 欢迎来到 SO!请考虑发布reproducible example
  • 除了尝试提供一个可重复的示例之外,我认为作为一般规则,最好的开始方法是首先计算您想要绘制的值(箱中宠物的比率),以整洁的格式获得结果,然后担心绘制.
  • @yoland我添加了一个小数据集样本,在ggplot之前需要什么步骤?

标签: r ggplot2


【解决方案1】:

有许多方法可以进行 2-D 分箱。一种选择是可以让 {ggplot2} 为您制作垃圾箱,然后标准化为总数并重新绘制它。在这里,您首先使用原始计数构建了绘图,然后使用ggplot2::ggplot_build() 拉出计算的 bin 并执行标准group_by() %>% mutate(fract = x/sum(x)。然后你可以重新绘制。

library(tidyverse)

n <- 5000

d <- tibble(x = rnorm(n),
            y = rnorm(n),
            pet = fct_infreq(sample(
              c("cat", "dog", "fish", "bird"), n, T, prob = c(4, 3, 2, 1)
            )))
p <- d %>%
  ggplot(aes(x, y)) +
  geom_bin_2d(aes(fill = after_stat(count))) +
  facet_wrap( ~ pet)

# original plot of count per animal per bin
p

# get underlying data
e <- ggplot_build(p)$data[[1]]

# normalize and then re-plot
e %>% 
  mutate(pet = fct_recode(PANEL, cat = "1", dog = "2", fish = "3", bird = "4")) %>% 
  group_by(xbin, ybin) %>% 
  mutate(fract = count/sum(count)) %>% 
  ggplot(aes(xmin, ymin)) +
  geom_tile(aes(fill = fract)) +
  facet_wrap(~pet)

创建于 2022 年 11 月 9 日,reprex v2.0.2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    相关资源
    最近更新 更多