I am making a rmarkdown document in which I want to display a ggplot chart using ggplotly and include the legend below it.
To that end, I extract the legend from the ggplot chart using the approach explained in: ggplot separate legend and plot
The problem I find is that the "margins" (or the canvas) of the legend are huge and the legend is shown far away from my main plot. I would like to remove those margins so the plot and the legend are displayed next to each other.
I tried the functions viewport()
and grid.newpage()
, but, I do not really understand what is going on under the hood when drawing a grob.
Is there a way to remove the margins from the legend?
Next I include the reproducible example:
---
title: "Stackq"
output: html_document
---
```{r setup, include=FALSE,echo=FALSE}
library(plotly)
library(ggplot2)
library(RColorBrewer)
library(grid)
library(cowplot)
df<-data.frame(x=runif(1000),y=runif(1000),z=rnorm(1000))
#function to extract the legend
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
```
```{r plotlyfig,echo=FALSE}
rf <- colorRampPalette(rev(brewer.pal(11,'Spectral')))
r <- rf(32)
p1 <-ggplot(df,aes(x=x,y=y,z=z))+ coord_fixed(ratio=1)+
stat_summary_hex(bins=100)+scale_fill_gradientn(colours=r)+ theme(legend.position="bottom")
p1leg<-g_legend(p1)
#using cowplot (the issue seems to be the same)
#p1leg<-cowplot::get_legend(p1)
p1<-p1+ theme(legend.position="none")
#print as ggplotly
ggplotly(p1)
```
```{r standalone_leg,echo=FALSE}
grid.draw(p1leg)
```