如何在 R 中创建 marginal/histogram 图和 geom_count 图?

How to create marginal/histogram plot along with a geom_count plot in R?

似乎,当使用 geom_count 然后绘制边缘时,它考虑了聚合点,但没有考虑它们的 size/counts,因此导致错误的边缘。

请参阅下面使用 geom_countgeom_point 的边际结果。

library(ggplot2)
library(ggExtra)
data(mpg, package="ggplot2")

mpg_select <- mpg[mpg$hwy >= 35 & mpg$cty > 27, ]
g <- ggplot(mpg, aes(cty, hwy)) +
  geom_count(show.legend = F)  
ggMarginal(g, type = "histogram", fill="transparent")
dev.copy(png,"/tmp/test01.png")
dev.off()

g <- ggplot(mpg, aes(cty, hwy)) +
  geom_point()
ggMarginal(g, type = "histogram", fill="transparent")
dev.copy(png,"/tmp/test02.png")
dev.off()

我怎样才能创建一个 geom_count 图,并且仍然得到如果我使用 geom_point 时会给出的边缘?

您可以使用 cowplot 包而不是 ggExtra 包来做到这一点。

library(tidyverse)
library(cowplot)

g <-
  ggplot(mpg, aes(cty, hwy)) +
  geom_count(show.legend = F)  

xhist <- 
  axis_canvas(g, axis = "x") + 
  geom_histogram(data = mpg,
                 aes(x = cty),
                 binwidth = 1,
                 color = 'lightgray')
yhist <- 
  axis_canvas(g, axis = "y", coord_flip = TRUE) + 
  geom_histogram(data = mpg,
                 aes(x = hwy),
                 binwidth = 1,
                 color = 'lightgray') +
  coord_flip()

g %>%
  insert_xaxis_grob(xhist, grid::unit(1, "in"), position = "top") %>%
  insert_yaxis_grob(yhist, grid::unit(1, "in"), position = "right") %>%
  ggdraw()