简体   繁体   中英

Change axis title position in ggplot using plotly

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM