plotly::ggplotly() is an R function that converts a ggplot2::ggplot() object to a plotly object. It is an incredible tool to create interactive web-based graphs with ggplot2::ggplot aesthetics. You can also easily manipulate a ggplotly object with the style function. An easy example of plotly::ggplotly() is given below.

    ````{r}
    library(ggplot2)
    library(plotly)

    p <- ggplot(mpg, aes(displ, hwy, colour = class)) + 
      geom_point()
    ggplotly(p)
    ```

The interactive features of the plotly::ggplotly() function can be super useful while displaying a plot output in a shiny application. If you have used plotly::ggplotly() inside a shiny application within a renderPlotly() context, you might have noticed the sizing and label placements is not accurate by default. This is because while converting a ggplot object to a ggplotly object, plotly::ggplotly() uses the size of the current graphic device, and if no device is located or provided, the default values are 640 for width and 800 for height. These default values might not be appropriate for all your shiny application so the placement of the labels is not always correct. An easy fix to this problem is to specify the height and width of the plot output container in a shiny app. The easiest way to do this is to create a new function, call it ggplotly2, that modifies the original plotly::ggplotly() function to customize the width and height of the plot output based on the container.

    ```{r}
    library(plotly)
    
    # Let ggplotly() know about the size of it's output container
    # (only works when being called within a renderPlotly() context)
    ggplotly2 <- function(x, ...) {
      info <- shiny::getCurrentOutputInfo()
      height <- if (is.function(info$height)) info$height()
      width <- if (is.function(info$width)) info$width()
      plotly::ggplotly(x, width = width, height = height, ...)
    }
    ```

Note that the customizing only works when called within a renderPlotly() context. Now, you can use the function ggplotly2() instead of plotly::ggplot() to convert a ggplot object to a ggplotly plot output with proper sizing and label placement inside a shiny application.

     ````{r}
    library(ggplot2)
    p <- ggplot(mpg, aes(displ, hwy, colour = class)) + 
      geom_point()
    ggplotly2(p)
    ```

You can use a similar method to modify a Plotly object based on other container information like foreground color, background color, font style etc. For shiny users, this is a good example of controlling codes to run at the different life cycle of shiny application, which is a pretty handy tool.