Plotly: Adding ggplotly() to the end of a pipe operation

Created on 1 Apr 2018  路  3Comments  路  Source: ropensci/plotly

I'm very used to the ggplot syntax and generate most plots with that library. Now and again, I'd like to turn my ggplotinto a plotlyplot. ggplotly ()works great for this.

data("diamonds")

library(ggplot2)
library(plotly)

data("cars")

p <- ggplot(diamonds,aes(carat,price)) +
  geom_point()

p %>%
  ggplotly()

It would be really elegant if one could add ggplotly() at the very end via piping. It nearly works, as shown in the code above. The following code however produces an error:

ggplot(diamonds,aes(carat,price)) +
  geom_point() %>%
  ggplotly()

#> Error in UseMethod("ggplotly", p) : 
#> no applicable method for 'ggplotly' applied to an object of class "c('LayerInstance', 'Layer', 'ggproto', 'gg')"

Most helpful comment

My workaround, adding parentheses around the expression before piping to ggplotly():
( ggplot(diamonds,aes(carat,price)) +
geom_point() ) %>%
ggplotly()

All 3 comments

How about something like this (untested)?

ggplot(diamonds,aes(carat,price)) %>%
  + geom_point() %>%
  ggplotly()

If it were possible to make %>% into a generic function, this might be doable, but I don't think R allows infix operators to be generic. If that is in fact true, I don't think this will be possible (I'd be happy to be proven otherwise)

My workaround, adding parentheses around the expression before piping to ggplotly():
( ggplot(diamonds,aes(carat,price)) +
geom_point() ) %>%
ggplotly()

Was this page helpful?
0 / 5 - 0 ratings