David Jorquera
David Jorquera

Reputation: 2102

Autosize height of ggplotly in shiny

I have a very high plotlyOutput (because it has many categories on the y axis). If It's rendered just with ggplotly(g), I get this plot, with a fixed height: Very short plot

So I specify it's height, like this: ggplotly(g, height = 1500), I get an appropiate size (the following is a fraction of the plot because of it's size): enter image description here

My problem is that when I filter the data through my app's input controls, It maintains the height (cause its now fixed), even when there are very few categories on the y axis. Like this (the following is a fraction of the plot because of it's size):

enter image description here

So, ¿how can I get dynamic height for my plotlyOutput, such as when there's, say, 3 categories on the y axis, It adjust the height to be shorter, but building to a maximum of 1500px as the number of categories increases?

Upvotes: 0

Views: 340

Answers (1)

Stéphane Laurent
Stéphane Laurent

Reputation: 84529

I don't see any solution except this one, which calculates the height in function of the number of categories in the plot:

library(shiny)
library(plotly)

dat <- data.frame(
  Letter = c(LETTERS,letters),
  height = rpois(52, 10)
)

ui <- fluidPage(
  checkboxInput("filter", "Filter"),
  plotlyOutput("ggly", height = "100%")
)

server <- function(input, output, session){

  output[["ggly"]] <- renderPlotly({
    ggdat <- if(input[["filter"]]) dat[dat$Letter %in% c("A","B"),] else dat
    height <- nlevels(droplevels(ggdat$Letter)) * 30
    gg <- ggplot(ggdat) + geom_col(aes(x = Letter, y = height)) + coord_flip()
    ggplotly(gg, height = min(1500, max(300, height)))
  })

}

shinyApp(ui, server)

Upvotes: 2

Related Questions