3

I have a ggplotly output based on geom_col() for which the number of bars varies significantly. I'd like to configure it so the spacing between bars (and therefore also the bar width) remains constant no matter how many bars there are, which means changing the plot height. Below is based on this solution but has no effect for me. Any suggestions appreciated.

require(tidyverse)
require(shiny)
require(plotly)

ui = fluidPage(
  sidebarPanel(width = 3, 
      sliderInput('count', 'count', min = 3, max = 100, value = 100, step = 25)
  ),
  mainPanel(width = 9, 
      div(plotlyOutput("plot", height = '200vh'), 
          style='height:90vh !important; overflow:auto !important; background-color:yellow;')
  )
)

server <- function(input, output, session) {
  
  output$plot = renderPlotly({
    d = data.frame(x = head(sentences, input$count), y = rlnorm(input$count, meanlog = 5))
    p = d %>% ggplot(aes(fct_reorder(x, y), y)) +
      geom_col(width = 0.1, col='grey90') + geom_point(size = 2) + 
      coord_flip() +
      theme_minimal(base_size = 12) + theme(panel.grid.major.y = element_blank())
    pltly = ggplotly(p) %>% layout(xaxis = list(side ="top" ))
    pltly$height = nrow(d) * 15
    pltly
  })
  
}

shinyApp(ui = ui, server = server,
         options = list(launch.browser = FALSE))

enter image description here

1 Answer 1

3

You can specify width/height in ggplotly() or plot_ly():

library(tidyverse)
library(shiny)
library(plotly)

ui = fluidPage(
  sidebarPanel(width = 3, 
               sliderInput('count', 'count', min = 3, max = 100, value = 100, step = 25)
  ),
  mainPanel(width = 9, 
            plotlyOutput("plot"),
  )
)

server <- function(input, output, session) {
  output$plot = renderPlotly({
    d = data.frame(x = head(sentences, input$count), y = rlnorm(input$count, meanlog = 5))
    p = d %>% ggplot(aes(fct_reorder(x, y), y)) +
      geom_col(width = 0.1, col='grey90') + geom_point(size = 2) + 
      coord_flip() +
      theme_minimal(base_size = 12) + theme(panel.grid.major.y = element_blank())
    pltly = ggplotly(p, height = nrow(d) * 15) %>% layout(xaxis = list(side ="top" ))
    pltly
  })
}

shinyApp(ui = ui, server = server, options = list(launch.browser = TRUE))

However, you might want to specify a bigger minimum height, using the first option, the plot becomes quite narrow.

Sign up to request clarification or add additional context in comments.

3 Comments

I'd already tried that but guess my ui code was defeating it. Thanks :)
Are you sure? For me it also works with your original UI code (if height is called in ggplotly).
I think my height calculation was way off.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.