2015-05-24 23 views
2

我想弄清楚如何在ShockPlot的renderPlot函數中創建「height」變量從renderPlot()中接收變量。這是server.R我的代碼:如何使renderPlot()中的「height」參數在Shiny R包中動態化

shinyServer(function(input, output) { 
output$contents <- renderPlot({ 
file<-input$file #a CSV file is uploaded 

file<-with(file, 
        aggregate(file[, input$metricIn], 
        by=list(period=day, 
        dimension1=file[, input$dimension1In], 
        dimension2=file[, input$dimension2In]), 
        FUN = input$funIn, na.rm=TRUE)) 
#input$dimension1In is column name from file 
#input$dimension2In is column name from file 

#count of facets in the plot to calculate height in renderPlot height argument 
facetCount<<-as.numeric(length(unique(file[, input$dimension1In]))) * 100 


plot<-reactive({  
    g<-ggplot(data = file, aes_string(x=input$dimension2In, 
            y=input$metricIn, fill=period)) 
    plot<-g + geom_bar(stat="identity", position=position_dodge()) + 
    facet_wrap(as.formula(paste("~", input$dimension1In)), 
       scales = "free", ncol=1) 
}) #end of reactive 
    print(plot()) 
}, width=1000, 
height = facetCount) 

}) #end of shinyServer 

所以我的問題是高度的說法是renderPlot沒有看到facetCount變量,甚至當我使用< < - 分配裏面renderPlot。

我想讓高度動態,因爲如果有很多方面要繪製,我希望繪圖高度相應地進行調整。

回答

1

當您的繪圖高度僅取決於某些輸入值時,請按照this question的答案。主要變化是在ui.R文件中使用uiOutput而不是plotOutput,因此也在server.R文件中將plotOutput包含在renderUI中。

當你的例子是計算在服務器端的情節的高度,像上面,您需要額外的函數調用中plotOutput添加到height參數。我認爲這是必需的,因爲Shiny在製作實際情節之前使用了高度參數。下面的例子爲我工作。

ui.R:

shinyUI(fluidPage(
    titlePanel("The plot height depends on a calculated value"), 
    # Sidebar with a slider input for a number 
    sidebarLayout(
     sidebarPanel(
      sliderInput("dimension1In", 
         "Choose a number:", 
         min = 20, 
         max = 50, 
         value = 30) 
      ), 
     # use uiOutput instead of plotOutput directly 
     mainPanel(
      uiOutput('ui_plot') 
     ) 
    ) 
)) 

server.R:

shinyServer(function(input, output) { 
    # instead of global assignment use reactive values 
    values <- reactiveValues() 
    # function where you do all the processing, e.g. read file, get data from it 
    file_processing <- function() { 
     # imagine this coefficient comes from your file 
     coefficient <- 10 
     return(coefficient) 
    } 
    # this function defines a height of your plot 
    plot_height <- function() { 
     # calculate values$facetCount 
     values$facetCount <- as.numeric(input$dimension1In) * file_processing() 
     return(values$facetCount) 
    } 
    # this function defines your plot, which depends on input$dimension1In 
    output$contents <- renderPlot({ 
     plot(1:input$dimension1In) 
    }) 
    # wrap plotOutput in renderUI 
    output$ui_plot <- renderUI({ 
     plotOutput("contents", height = plot_height(), width = "100%") 
    }) 

})