Change axis title position in ggplot using plotly

2019-07-17 06:56发布

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.)

1条回答
欢心
2楼-- · 2019-07-17 07:21

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))
查看更多
登录 后发表回答