5

As shown in the image below, the height of my plot remains constant when multiple counties are selected in the sidebar. This makes the plot too crowded so that the labels become unreadable. I would like to alter the height of my plot as a function of the number of counties that are selected in the sidebar. How can I do this?

Below, please see part of my codes that I believe need to be modified.

enter image description here

UI element

mainPanel(plotOutput("workforce_plot"), 

server element

workforce_plot <- reactive({
     ggplot(workforce_data(), aes(x =Age_Group, y = Percentage, fill=County.y)) + 
     geom_bar(stat = "identity",position = position_dodge()) +                                                         
     geom_text(
     aes(label = Percentage2),
     vjust = 0.5,
     colour = "black", 
     position = position_dodge(width=0.9),
     fontface = "bold",
     size=3.2,
     hjust = 0)+
     ylim(0,110)+        
     coord_flip()+

     labs(
          x = "Age Groups",
          y = "Percentage",
          face = "bold")
          })

   output$workforce_plot <- renderPlot ({ 
            workforce_plot()
          })
Nader Mehri
  • 514
  • 1
  • 5
  • 21
  • 1
    Would the 'shinyjqui' package be of interest? It has a function called 'jqui_resizable()' which lets the shiny user resize the plot image. Read more here: https://github.com/Yang-Tang/shinyjqui – bs93 Apr 07 '20 at 13:22
  • 1
    Also how about the accepted answer to this question: https://stackoverflow.com/a/17209387/11437205 – bs93 Apr 07 '20 at 13:30

1 Answers1

6

You can add a height parameter to your renderPlot function, and pass a function to it that adjusts the height based on some relevant reactive.

One example:

output$workforce_plot <- renderPlot ({ 
            workforce_plot()
          }, height = function() {200 + (length(workforce_data()[["County.y]]) *.2)})

(It could also be something like length(input$country) instead of a reactive expr.)

Then in ui.R define height = 'auto' for that panel.

user12728748
  • 8,106
  • 2
  • 9
  • 14
  • Thanks! This perfectly worked for me! Can I do the same thing for the labels? Also, I was wondering if there is any way to add a tiny gap between bars within each age group so that the labels become readable enough when multiple counties are selected? Please see the updated above plot. – Nader Mehri Apr 07 '20 at 22:51
  • @Nader - To get a gap between dodged bars, you can change the dodge width, e.g.: `geom_bar(stat = "identity", position = position_dodge2(width = .9, preserve = "single")) `. – user12728748 Apr 08 '20 at 04:19
  • Thanks! I added the suggested code, but it did not make any change. – Nader Mehri Apr 08 '20 at 05:34