Search code examples
rggplotly

How to set the font size in ggplotly?


I have made a ggplot

library(ggplot2)
library(ggplotly)

f1 <- diamonds |> group_by(cut,clarity,color) |>  count() |> 
  group_by(cut) |> mutate(N=sum(n)) |> 
      ggplot() +
      aes(
        x =  cut,
        y = n,
        fill = cut
      ) +
      geom_col() +
      theme(legend.position = "none")+
      coord_flip()+
  facet_wrap(vars(clarity))
f1

I want to convert to ggplotly object

ggplotly(f1)%>% 
        layout(legend=list(font = list(size = 8)), 
            xaxis = list(titlefont = list(size = 8), tickfont = list(size = 8)),
            yaxis = list(titlefont = list(size = 8), tickfont = list(size = 8)))

However, the size of text is only changed in the 1st subplot. I would like to have the size applied to all subplots:

enter image description here

The issue is I have it in a function so number of facets varies, so this post was not helpful: R ggplotly with facet_wrap : axis tick size not changing for all plots


Solution

  • As already pointed out in the answer in the referenced post you have to style each axis separately, i.e. in contrast to ggplot2 each subplot or facet in plotly has it's own axis. As a consequence, xaxis and yaxis will only have an effect on the first row or column of the facet panels.

    library(ggplot2)
    library(plotly, warn=FALSE)
    
    axis <- list(tickfont = list(size = 8))
    
    ggplotly(f1) %>%
      layout(
        xaxis = axis,
        xaxis2 = axis,
        xaxis3 = axis,
        yaxis = axis,
        yaxis2 = axis,
        yaxis3 = axis
      )
    

    For that reason IMHO the easier approach would be to style your axes directly in ggplot2 using theme options:

    f2 <- f1 +
      theme(axis.text = element_text(size = 6))
    
    ggplotly(f2)