5

I wish to make a ggplot object interactive using plotly. When I use ggplotly(), huge white spaces are introduced between my facets, making the plot small and weird looking:

plotly facets

Compared to how big and neat it looks when using ggplot only:

ggplot object

My reproducible code is:

library(plotly)
library(ggplot2)
library(reshape2)

p <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + 
  geom_point(shape=1) + 
  facet_wrap( ~ day, ncol=2)

ggplotly(p)

I don't know if its my computer settings or something is wrong with my code. Am using R version 4.0.2, ggplot2 version 3.3.2 and plotly version 4.9.2.1. Someone help me retain the size and add interactivity to my plot.

I have tried the answer given here by Cam McMains but nothing changes.

Update

library(plotly)
library(ggplot2)
library(reshape2)

p <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + 
  geom_point(shape=1) + 
  theme(panel.spacing=unit(0,'npc'))+
  facet_wrap( ~ day, ncol=2)
  
ggplotly(p)

Gives update

F.Mueni
  • 51
  • 4
  • So if you set `theme(panel.spacing=unit(0,'npc')` (or something otherwise very small), does that fix things in your `ggplotly()` plot? – chemdork123 Jul 30 '20 at 21:19
  • @chemdork123 that collapses the horizontal plots together and reduces the distance between the vertical plots. See update above. – F.Mueni Jul 31 '20 at 07:17
  • Interesting. I don't have your `tips` dataframe, but when I try using `mtcars`, I'm not getting the large vertical spacing you you. Reprex: `ggplot(mtcars, aes(mpg, disp)) + geom_point() + facet_wrap(~factor(carb))`. Does that change anything for you? – chemdork123 Jul 31 '20 at 12:34
  • @chemdork123 try maximizing your plot by zooming and see if the white spaces appear. – F.Mueni Jul 31 '20 at 13:25
  • The spaces appear... but only slightly larger and nothing like in your example. Scaling is similar to (but not exactly like) the same plot using `ggplot2` alone. – chemdork123 Jul 31 '20 at 15:16
  • Try saving as an HTML widget: `library(htmlwidgets)`, then `saveWidget(ggplotly(p), 'test.html')` should do it. When you open the resulting html in a browser, do you still see the same spacing? – chemdork123 Jul 31 '20 at 15:22
  • @F.Mueni interesting. I ran your code and white spaces are just the same size as when using ggplot. I am on R 3.6.3, plotly 4.9.2.1. Did you solve the problem? – johnjohn Aug 10 '20 at 08:55
  • @johnjohn I haven't solved the problem yet, maybe this is happening because of my computer settings. – F.Mueni Aug 11 '20 at 10:02

0 Answers0