3

I have an issue when using ggplotly on a ggplot graph. It is basically the exact same issue as here. However, the offered solution does not work if the plot is not facetted, since the object gp[['x']][['layout']][['annotations']] that should be altered does not exist in this case. (Unfortunately, I don't have enough reputation to comment, therefore I have to raise the issue as a new question.) As a result, I cannot find how to adjust the y axis title position in a non-faceted plot. This is the working example from the other question

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)
gp[['x']][['layout']][['annotations']][[2]][['x']] <- -0.1
gp %>% layout(margin = list(l = 75))

And this is the non-working counterpart:

p <- ggplot(gapminder, aes(x = gdpPercap, y = lifeExp)) + 
  geom_point() + 
  scale_x_log10()
gp <- ggplotly(p)
gp[['x']][['layout']][['annotations']][[2]][['x']] <- -0.1
gp %>% layout(margin = list(l = 75))

(NOTE: in this specific example, there is no overlap between axis title and axis labels, however I wanted to point out the fact that axis title re-positioning does not work based on the same example.)

Bart VdW
  • 438
  • 8
  • 17

1 Answers1

4

Here is a trick that solves your problem:

library(gapminder)
library(plotly)

gapminder$grp <- ""
p <- ggplot(gapminder, aes(x = gdpPercap, y = lifeExp)) + 
  geom_point() + 
  scale_x_log10() + 
  facet_wrap(~grp)
gp <- ggplotly(p) 
gp[['x']][['layout']][['annotations']][[2]][['x']] <- -0.1
gp %>% layout(margin = list(l = 75))
Marco Sandri
  • 23,289
  • 7
  • 54
  • 58
  • Can you explain why this works? Is there any other way to address this issue? – Bjørn Kallerud Jul 17 '19 at 20:11
  • The trick is simple. The solution described by Bart does not work if the plot is not facetted. Hence, I use a fake facetting by `facet_wrap(~grp)`, where `grp` is a column with empty strings. – Marco Sandri Jul 17 '19 at 20:20
  • Right - love the workaround. I guess my question was more along the lines of - why does facetting turn the title into an annotation, and why can't we move titles in `ggplotly`? – Bjørn Kallerud Jul 17 '19 at 20:24
  • 1
    Ah, OK. I have no answer, sorry. Maybe you can find the answer following the links given by Bart. Good luck ! – Marco Sandri Jul 17 '19 at 20:45