使用ggplot facets时,增加闪亮的绘图大小

时间:2018-06-18 17:06:41

标签: r ggplot2 shiny

是否有办法根据.php图中使用的构面数量增加shiny中的绘图窗口大小 - 可能使用垂直滚动。

例如,使用下面的示例,当输入为ggplot时,有三个方面,并且图表看起来很好。选择选项"A"时,绘图数量会增加,但绘图窗口保持相同的大小,导致绘图太小。

是否有策略保持所有面板高度不变,与输入无关?感谢。

"B"

2 个答案:

答案 0 :(得分:3)

您可以在下面找到一个工作示例:

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)

由于以下帖子,这个答案是可能的:

答案 1 :(得分:2)

如果使用facet_wrap而不是facet_grid,则应将Aurelien callens提供的gg_facet_nrow函数修改为:

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
}

如果定义了列数,则该函数可以编写如下:

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
}

除了更改为facet_wrap以外,Aurelien callens答案中提供的其他代码保持不变。

相关问题