I need to create a shiny app in which the user decides how many charts to display and in how many columns via sliders.
To merge the graphs I used the function grid.arrange
but it is not mandatory, the important thing is to have ggplot objects. And I need coord_fixed()
.
This is a small executable example:
library(shiny)
library(shinythemes)
library(readr)
library(ggplot2)
library(dplyr)
library(tidyr)
library(grid)
library(gridExtra)
library(ggforce)
library(shinythemes)
ui <- fluidPage(
navbarPage("MotorBrain",
tabPanel("Configurazione",
sidebarLayout(
sidebarPanel(
sliderInput("input1", "N. utenti",
min = 1, max = 133,
value = 3),
sliderInput("nCol1", "Ncols",
min = 1, max = 32,
value = 1),
actionButton("goButton1", "Visualizza")),
fluidRow()))),
tabPanel("Visualizzazione",
fluidRow(
uiOutput("outputTest1"))
))
server <- function(input, output,session) {
input1<-eventReactive(input$goButton1,{
input$input1
})
output$outputTest1 <- renderUI({
pl <- vector("list", length = input1())
for(t in 1: input1()) {
p<-ggplot()
geom_point(x=runif(10000,0, 1),y=runif(500,0, 1))
coord_fixed()
pl[[t]] <-p
}
output$plot_test1<- renderPlot({
grid.arrange(grobs=pl,ncol=input$nCol1,top="")
})
plotOutput(outputId = "plot_test1")
})
}
shinyApp(ui = ui, server = server)
I need to add two more sliders with which the user can decide how much horizontal and vertical white space to put between the various graphs in the grid. How can I do this?
CodePudding user response:
gridExtra
added uncontrollable space between columns, so one solution is to use patchwork
instead, where no extra space is added. Then we can use margin
tricks to add space:
library(shiny)
library(shinythemes)
library(readr)
library(ggplot2)
library(dplyr)
library(tidyr)
library(grid)
library(ggforce)
library(patchwork)
ui <- fluidPage(
navbarPage("MotorBrain",
tabPanel("Configurazione",
sidebarLayout(
sidebarPanel(
sliderInput("input1", "N. utenti",
min = 1, max = 133,
value = 3),
sliderInput("nCol1", "Ncols",
min = 1, max = 32,
value = 1),
sliderInput("h_space", "top bottom space (pt)",
min = 1, max = 100,
value = 1),
sliderInput("v_space", " left right space (pt)",
min = 1, max = 100,
value = 1),
actionButton("goButton1", "Visualizza")),
fluidRow()))),
tabPanel("Visualizzazione",
fluidRow(
uiOutput("outputTest1"))
))
server <- function(input, output,session) {
input1<-eventReactive(input$goButton1,{
input$input1
})
output$outputTest1 <- renderUI({
pl <- vector("list", length = input1())
for(t in 1: input1()) {
p<-ggplot()
geom_point(x=runif(10000,0, 1),y=runif(500,0, 1))
coord_fixed()
# the space is added to both sides, so we need to reduce by half
theme(plot.margin = unit(c(
input$h_space/2,
input$v_space/2,
input$h_space/2,
input$v_space/2
), "pt"))
pl[[t]] <-p
}
output$plot_test1<- renderPlot({
Reduce(` `, pl)
plot_layout(ncol = input$nCol1)
})
plotOutput(outputId = "plot_test1")
})
}
shinyApp(ui = ui, server = server)