R: ggplot and plotly axis margin won't change

Let's use a simple reproducible example from here.

library(gapminder)
library(plotly)
p <- ggplot(gapminder, aes(x=gdpPercap, y=lifeExp)) + geom_point() + scale_x_log10()
p <- p + aes(color=continent) + facet_wrap(~year)
gp <- ggplotly(p)

enter image description here

We can move the adjust the margins as suggested by MLavoie but then our axis legend moves as well.

gp %>% layout(margin = list(l = 75))

enter image description here

The axis label is actually not a label but an annotation, so let's move it first. You can query the structure of the annotations in the graph gp:

# find the annotation you want to move
str(gp[['x']][['layout']][['annotations']]) 

List of 15
 $ :List of 13
  ..$ text          : chr "gdpPercap"
  ..$ x             : num 0.5
  ..$ y             : num -0.0294
  ..$ showarrow     : logi FALSE
  ..$ ax            : num 0
  ..$ ay            : num 0
  ..$ font          :List of 3
  .. ..$ color : chr "rgba(0,0,0,1)"
  .. ..$ family: chr ""
  .. ..$ size  : num 14.6
  ..$ xref          : chr "paper"
  ..$ yref          : chr "paper"
  ..$ textangle     : num 0
  ..$ xanchor       : chr "center"
  ..$ yanchor       : chr "top"
  ..$ annotationType: chr "axis"
 $ :List of 13
  ..$ text          : chr "lifeExp"
  ..$ x             : num -0.0346
  ..$ y             : num 0.5
.... <truncated>

Ok, so annotations are stored in a list of 15; "lifeExp" is the second([[2]]) element of this list. The "x" ([['x']]) and "y" values control the movement left and right/up and down in this case, respectively.

# Check current x-location of x-axis label
gp[['x']][['layout']][['annotations']][[2]][['x']]
[1] -0.03459532

# Move the label further to the left
gp[['x']][['layout']][['annotations']][[2]][['x']] <- -0.1
gp %>% layout(margin = list(l = 75))

enter image description here


Find an answer from Github that solved this problem elegantly.

layout_ggplotly <- function(gg, x = -0.02, y = -0.08){
  # The 1 and 2 goes into the list that contains the options for the x and y axis labels respectively
  gg[['x']][['layout']][['annotations']][[1]][['y']] <- x
  gg[['x']][['layout']][['annotations']][[2]][['x']] <- y
  gg
}
gp %>% layout_ggplotly

Tags:

R

Ggplot2

Plotly