I have a dashboard that have a number of graphs (created in ggplot then converted into plotly plots with ggplotly()
arranged in columns of two within fluidRows()
:
However, when the browser window is minimised, the bar sizes adjust automatically, but the x-axis labels become squashed together:
How can I dynamically adjust the number of x-axis breaks based on browser window width? I know I can get the dimensions of the browser window using code from this question, and I had the idea of creating a reactive value based on the window width that I could then pass to breaks
in scale_x_discrete()
, but I haven't been able to bring the entire thing together.
I need a solution that will work regardless of what discrete values are on the x-axis, since I have about ~20 different graphs with different values, e.g. some may be be 'Level1 - Level10', others may be different codes, e.g. AEF01 - AEF10.
Reproducible code:
library(shiny)
library(plotly)
library(tidyverse)
dat <- data.frame(
x = factor(rep(paste0("Level", 1:10)),
levels = c("Level1", "Level2", "Level3", "Level4", "Level5", "Level6",
"Level7", "Level8", "Level9", "Level10")),
y = rep(runif(10, 20, 100))
)
ui <- fluidPage(
fluidRow(
column(
width = 6,
plotlyOutput("plot")
)
)
)
server <- function(input, output) {
output$plot <- renderPlotly({
plot <- dat %>%
ggplot(aes(x = x, y = y, fill = y)) +
geom_bar(stat = "identity", position = "dodge")
ggplotly(plot)
})
}