Juan Sebastian Lozano Juan Sebastian Lozano - 3 months ago 95
R Question

Plotly axis labels overlapping and being too big

I'm using plotly with

R
and
shiny
, and
ggplot2
. When outputting a plot (like below) where the tick labels are too big, the axis label overlaps with the tick label, as shown:

#UI.R
library(shiny)
library(plotly)
library(ggplot2)

shinyUI(fluidPage(
plotlyOutput("Plot")
))

#Server.R

shinyServer(function(input, output) {

output$Plot <- renderPlotly({

plot <- ggplot(diamonds, aes(x=cut)) +
geom_bar()+
theme(axis.text.x = element_text(angle = 90, size = 25))
ggplotly(plot)

})

})


which outputs: bad plot

You can see that the larger tick marks overlap the label (in this case "cut"). Although I made this example by making the font bigger, the same thing happens with long labels. Moreover, sometimes the entire label isn't visible (i.e. it goes 'out of frame'), like so (taken from a different project):overflow plot

I want to make this behave more like ggplot2, which outputs: good plot

Does anyone know a way of doing this? I can not find much good documentation on how to change something coming from ggplotly.

Answer

Use plotly_build() to adjust the margins. From the documentation:

Using this function can be useful for overriding defaults provided by ggplotly/plot_ly or for debugging rendering errors.

pb <- plotly_build(plot)
str(pb)
pb$layout$margin$b <- 220
pb

enter image description here