Keep aspect ratio when using ggplotly

2019-05-12 17:59发布

I have a ggplot hexbin chart that I want to show with ggplotly. However, when I use the ggplotly function the aspect ratio, previously fixed for the gplot chart, is lost.

Minimal working example:

library(ggplot2)
library(plotly)
library(RColorBrewer)

set.seed(11)
df<-data.frame(xvar=rnorm(1000,0,4),yvar=rnorm(1000))

#nicer colours
palette <- colorRampPalette(rev(brewer.pal(11,'Spectral')))
colours<-palette(32)

p1<-ggplot(df,aes(x=xvar,y=yvar))+ coord_fixed(ratio=1)+
  stat_binhex(bins=50)+scale_fill_gradientn(colours=colours)
p1
ggplotly(p1)

I have approximated the ratio with the following code but the ratio is still slightly wrong because of the legend.

ratioaxes<-(max(df$yvar)-min(df$yvar))/(max(df$xvar)-min(df$xvar))
ggplotly(p1,height=ratioaxes*500,width=500)

Is there any way that I can preserve this ratio?

Thanks in advance!

标签: r ggplot2 plotly
0条回答
登录 后发表回答