rggplot2plotlyggplotly

ggplotly with facets and rotation of x-axis labels


I'm using ggplotly to make my plots interactive inside a Shiny app. I need to rotate the x-axis labels by 45 degrees. This works fine, but only until I have facets. If my plot has facets, then only the left facet gets rotated axis labels, whereas other facets do not. I haven't seen this addressed elsewhere... Below is sample code showing the rotation working fine in a single-panel plot and breaking with facets.

library(dplyr)
library(ggplot2)
library(plotly)

df <- expand.grid(x = 1:10, group = c("a", "b"))
p <- ggplot(df) +
        geom_point(aes(x = x, y = x))
ggplotly(p) %>% layout(xaxis = list(tickangle = -45))

p <- p + facet_wrap(~ group)
ggplotly(p) %>% layout(xaxis = list(tickangle = -45))
    

Solution

  • You could either take care of that in ggplot2 with theme() or set xaxis2 to be at -45° in layout().

    library(dplyr)
    library(ggplot2)
    library(plotly)
    
    df <- expand.grid(x = 1:10, group = c("a", "b"))
    
    p <- ggplot(df) +
      geom_point(aes(x = x, y = x))
    
    p <- p + facet_wrap(~ group)
    ggplotly(p) %>% layout(xaxis = list(tickangle = -45),
                           xaxis2 = list(tickangle = -45))
    

    p <- ggplot(df) +
      geom_point(aes(x = x, y = x)) +
      theme(axis.text.x = element_text(angle = 45))
    
    
    p <- p + facet_wrap(~ group)
    ggplotly(p)