有没有办法根据图形shiny中使用的方面的数量增加绘图窗口的大小ggplot- 可能使用垂直滚动。
例如,使用下面的示例,当输入是"A"三个方面时,图看起来不错。选择选项时"B",绘图的数量增加,但绘图窗口保持相同的尺寸,从而导致绘图太小。
是否有一种策略可以保持所有面板高度相同,独立于输入?谢谢。
library(ggplot2)
library(shiny)
mtcars$cyl = sample(letters[1:5], 32, TRUE)
ui <- fluidPage(
navbarPage(title="title",
tabPanel("One",
column(3,
wellPanel( selectInput('name', 'NAME', c("A", "B")))),
column(9, plotOutput('plot1')))
))
server <- function(input, output) {
X = reactive({input$name == "A"})
output$plot1 <- renderPlot({
if(X()){
p1 = ggplot(mtcars, aes(mpg, wt)) + facet_grid( . ~ gear )
}else{
p1 = ggplot(mtcars, aes(mpg, wt)) + facet_grid( cyl ~ gear )
}
return(p1)})
}
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)
如果使用facet_wrap而不是facet_grid,则gg_facet_nrowAurelien callens 提供的函数应修改为:
gg_facet_nrow <- function(p){
num_panels <- length(unique(ggplot_build(p)$data[[1]]$PANEL)) # get number of panels
num_rows <- wrap_dims(num_panels)[1] # get number of rows
}
Run Code Online (Sandbox Code Playgroud)
如果您已经定义了列数,则该函数可以编写如下:
gg_facet_nrow <- function(p){
num_panels <- length(unique(ggplot_build(p)$data[[1]]$PANEL)) # get number of panels
num_cols <- ggplot_build(p)$layout$facet$params$ncol # get number of columns set by user
num_rows <- wrap_dims(num_panels, ncol=num_cols)[1] # determine number of rows
}
Run Code Online (Sandbox Code Playgroud)
除了更改为 之外facet_wrap,Aurelien callens 答案中提供的其他代码保持不变。
小智 5
您可以在下面找到一个工作示例:
library(ggplot2)
library(shiny)
library(tidyverse)
mtcars$cyl = sample(letters[1:5], 32, TRUE)
gg_facet_nrow<- function(p){
p %>% ggplot2::ggplot_build() %>%
magrittr::extract2('layout') %>%
magrittr::extract2('panel_layout') %>%
magrittr::extract2('ROW') %>%
unique() %>%
length()
}
ui <- fluidPage(
navbarPage(title="title",
tabPanel("One",
column(3,
wellPanel( selectInput('name', 'NAME', c("A", "B")))),
column(9, plotOutput('plot1')))
))
server <- function(input, output) {
X <- reactive({input$name == "A"})
p1 <- reactive({
if(X()){
p1 <- ggplot(mtcars, aes(mpg, wt)) + facet_grid( . ~ gear )
}else{
p1 <- ggplot(mtcars, aes(mpg, wt)) + facet_grid( cyl ~ gear )
}
return(p1)
})
he <- reactive(gg_facet_nrow(p1()))
output$plot1 <- renderPlot({p1() }, height = function(){he()*300})
}
shinyApp(ui,server)
Run Code Online (Sandbox Code Playgroud)
由于以下帖子,这个答案是可能的:
height = function(){he()*300}))gg_facet_nrow()) 中提取行数。