Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to facet a plot_ly() chart?

Tags:

r

r-plotly

Using ggplot2 and plotly to make an interactive scatter plot with facet_wrap().

library(ggplot2)
library(plotly)

g<-iris%>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width, color = Species))+
  geom_point()+
  facet_wrap(vars(Species))
ggplotly(g)

ggplot2 scatterplot with facet_wrap, rendered in plotly

Is it possible to "facet" using the plot_ly() function? The documentation suggests subplot()...

p<-iris%>%
  group_by(Species)%>%
  plot_ly(x = ~Sepal.Length, y = ~Sepal.Width, color = ~Species, type = "scatter")%>%
  subplot() ##Something else here? 
p

how to facet this plot_ly scatterplot?

like image 704
M.Viking Avatar asked Sep 25 '19 16:09

M.Viking


1 Answers

1: Facet a plot_ly chart using the do() and subplot() method:

library(plotly)
iris%>%
  group_by(Species) %>%
  do(p=plot_ly(., x = ~Sepal.Length, y = ~Sepal.Width, color = ~Species, type = "scatter")) %>%
  subplot(nrows = 1, shareX = TRUE, shareY = TRUE)

Plot_ly chart made with group_by() and do() function

2: Trellis a plot_ly chart using the new dplyr::group_map() function.

library(dplyr)
iris%>%
  group_by(Species) %>%
  group_map(~ plot_ly(data=., x = ~Sepal.Length, y = ~Sepal.Width, color = ~Species, type = "scatter", mode="markers"), keep=TRUE) %>%
  subplot(nrows = 1, shareX = TRUE, shareY=TRUE)
like image 144
M.Viking Avatar answered Sep 30 '22 07:09

M.Viking