In running the R Shiny code extract shown at the bottom of this post, I am trying to make the width of the 2 horizontally-rendered and jointly-rendered plots to roughly match the width of the data table that is rendered beneath the plots, and I am trying to make the height of the plots roughly equal their individual widths so they appear squarish. I have tried making the size of the plots dynamic as the width of the data table (in the full code this example is extracted from) changes. Is there a way to do this in R Shiny?
I have fooled around with the following using shinyjs
in my attempts to make this work, no luck yet:
observe({
runjs("
Shiny.onInputChange('tableWidth', $('#tableOutput').width());
")
})
# Print the table width to the console
observeEvent(input$tableWidth, {
print(paste("Data table width:", input$tableWidth))
})
The below image explains further:
Code extract:
library(DT)
library(ggplot2)
library(shiny)
line_a <- rnorm(10,0,1)
line_b <- rlnorm(10,0.2,0.5)
plotFun <- function(data, title) {
ggplot(data, aes(x = X)) +
geom_line(aes(y = Original), color = "blue") +
geom_line(aes(y = Fitted), color = "red", linetype = "dashed")
}
ui <- fluidPage(
sidebarPanel(
sliderInput("mult", "Apply multiple:", min = 1, max = 8, value = 2)
),
mainPanel(
plotOutput("showFitPlots"),
DTOutput("tableOutput")
)
)
server <- function(input, output, session) {
fit_lines <- reactive({
list(
a = data.frame(X = seq_along(line_a), Original = line_a, Fitted = line_a * input$mult),
b = data.frame(X = seq_along(line_b), Original = line_b, Fitted = line_b * input$mult)
)
})
output$showFitPlots <- renderPlot({
p1 <- plotFun(fit_lines()$a,"Line A")
p2 <- plotFun(fit_lines()$b,"Line B")
fitPlots <- ggarrange(p1, p2,nrow = 1,ncol = 2)
annotate_figure(fitPlots)
})
output$tableOutput <- renderDT({
data <- data.frame(
fit_lines()$a$Original,
fit_lines()$a$Fitted,
fit_lines()$b$Original,
fit_lines()$b$Fitted
)
datatable(
data,
container = tags$table(
tags$thead(
tags$tr(
tags$th("Period"),
tags$th("Original Line A"),
tags$th("Fitted Line A"),
tags$th("Original Line B"),
tags$th("Fitted Line B")
)
)
)
)
})
}
shinyApp(ui, server)