daattali / ggExtra

📊 Add marginal histograms to ggplot2, and more ggplot2 enhancements

Home Page:http://daattali.com/shiny/ggExtra-ggMarginal-demo/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cannot add ggproto objects together

idavydov opened this issue · comments

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

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

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