LEo
LEo

Reputation: 487

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

It seems that, when using a geom_count and then plotting the marginals, it take in account the aggregated dots, but does not consider their size/counts, therefore leading to a wrong marginal.

See bellow the marginal results using geom_count and geom_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()

enter image description here

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

enter image description here

How may I create a geom_count plot and still gets the marginals that would be given if I had used geom_point?

Upvotes: 0

Views: 786

Answers (1)

teru
teru

Reputation: 328

You can do that with cowplot package instead of ggExtra package.

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()

enter image description here

Upvotes: 1

Related Questions