daattali / ggExtra

📊 Add marginal histograms to ggplot2, and more ggplot2 enhancements
http://daattali.com/shiny/ggExtra-ggMarginal-demo/
Other
383 stars 45 forks source link

Cannot add ggproto objects together #136

Closed idavydov closed 5 years ago

idavydov commented 5 years ago

Hi,

Sorry, maybe this was already discussed before.

This code does not work:

library(tidyverse)
tibble(a=1:10, b=a**2) %>%
  ggplot(aes(a, b)) +
  geom_point() %>%
  ggExtra::ggMarginal(type="histogram")
#> Error: Cannot add ggproto objects together. Did you forget to add this object to a ggplot object?

While this does:

library(tidyverse)
p <- tibble(a=1:10, b=a**2) %>%
  ggplot(aes(a, b)) +
  geom_point()
ggExtra::ggMarginal(p, type="histogram")

Created on 2019-01-23 by the reprex package (v0.2.0).

crew102 commented 5 years ago

Hi @idavydov , this syntax won't work b/c %>% is taking precedence over + , so the example you gave gets evaluated like this:

(tibble(a=1:10, b=a**2) %>% ggplot(aes(a, b))) +
 (geom_point() %>% ggExtra::ggMarginal(type="histogram"))

ggMarginal() obviously needs more than just a layer (i.e., geom_point()) to do its thing, hence the error. You can override the precedence if you'd like, which should fix things:

library(tidyverse)
(tibble(a=1:10, b=a**2) %>%
  ggplot(aes(a, b)) +
  geom_point()) %>%
  ggExtra::ggMarginal(type="histogram")
idavydov commented 5 years ago

Thanks a lot for your explanation, that is very helpful.