I'm very used to the ggplot
syntax and generate most plots with that library. Now and again, I'd like to turn my ggplot
into a plotly
plot. 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')"
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()
Most helpful comment
My workaround, adding parentheses around the expression before piping to
ggplotly()
:( ggplot(diamonds,aes(carat,price)) +
geom_point() ) %>%
ggplotly()