ggplotly adjust label position

Hello @ryamy ,

I took a swing at this. I am not super conversant with plotly, but hereis what I observed.

  1. plotly works in slightly different manner when we convert a ggplot object to a plotly object using ggplotly() compared to creating plotly charts using plot_ly(). I say so after noticing this. I ran the code you have given, the standoff argument is making no difference, but it works when we provide text along with it. Take a look at below code and output
iris %>%
  ggplot(aes(x=Sepal.Length, y=Sepal.Width)) +
  geom_point() +
  theme(text=element_text(size=24)) +
  facet_wrap(~Species) -> g

 ggplotly(g) %>%
  layout(margin=list(l=300, r=100, b=100, t=100),
         xaxis=list(
           title=list(standoff=25)
         ),
         yaxis=list(
           title=list(text = "yellow water melon",standoff=50)
         ))


Notice that the yaxis title that is set by ggplot is not affected by operations in the layout(), but if the yaxis title is added in layout() then it works.

So there can be two ways around this, first, set axis titles in ggplot as NULL and then set axis titles in layout(). Second, create the chart using plot_ly() approach.

Just an example of the first way around:

iris %>%
  ggplot(aes(x=Sepal.Length, y=Sepal.Width)) +
  geom_point() +
  labs(
    x = NULL,
    y = NULL 
  )+
  theme(text=element_text(size=24)) +
  facet_wrap(~Species) -> g

 ggplotly(g) %>%
  layout(margin=list(l=300, r=100, b=100, t=100),
         xaxis=list(
           title=list(text = "Hakuna Matata", standoff=25)
         ),
         yaxis=list(
           title=list(text = "yellow water melon", standoff=50)
         ))

Not a very elegant solution but hope it helps,
Ayush

3 Likes