2013-07-14 53 views
5

我有一個關於R Shiny應用程序的常見問題:我有一個最終用戶可以從下拉菜單中選擇的ID列表(selectInput),我希望根據這個ID做出相應的情節。換句話說,所選變量將作爲繪圖函數中的參數傳遞,並且每次我選擇不同的ID時,繪圖也會改變。我能否知道這在Shiny中是否可行?我很感激任何人都可以提供類似問題的實例。謝謝!從下拉菜單中選擇一個變量,並將其作爲參數傳遞到R中的reactivePlot中Shiny

+0

這是絕對有可能有光澤。通讀http://rstudio.github.io/shiny/tutorial/#welcome,看看如何 –

回答

13

下面是一個以下拉爲參數的示例工作示例。這個程序的輸出可以在http://glimmer.rstudio.com/bishwamitrad/ggplot2browser/查看:

ui.R

library(shiny) 
library(ggplot2) 

## Define UI for miles per gallon application 

dataset <- diamonds 

title <- "Diamonds data Analysis" 

## Define UI for application that plots random distributions 

shinyUI(pageWithSidebar(

    ## Application title 
    headerPanel(title), 

    ## Sidebar with a slider input for number of observations 

    sidebarPanel (

    sliderInput('sampleSize','Sample Size', min=1, max=nrow(dataset), 
       value=min(1000,nrow(dataset)), 
       step=500, 
       round=0), 

    selectInput('x','X',names(dataset)), 
    selectInput('y','Y',names(dataset), 
       names(dataset)[[2]]), 

    selectInput('color','Color',c('None',names(dataset))), 

    selectInput('shape','Shape',c('None',names(dataset))), 

    checkboxInput('jitter','Jitter'), 
    checkboxInput('smooth','Smooth'), 

    selectInput('facet_col','Facet Column', 
       c(None='.',names(dataset))), 

    selectInput('facet_row','Facet Row', 
       c(None='.',names(dataset))) 

), 

    ## Show a plot of the generated distribution 

    mainPanel(plotOutput('plot',height="700px")) 


) 

) 

server.R

library(shiny) 
library(ggplot2) 

## Define server logic required to generate and plot a random distribution 
shinyServer(function(input,output) { 

    dataset <- reactive(function(){ 
    diamonds[sample(nrow(diamonds),input$sampleSize),] 
    }) 

output$plot <- renderPlot(function(){ 

    p <- ggplot(dataset(),aes_string(x=input$x, y=input$y))+geom_point() 

    if(input$color != 'None') 
    p <- p + aes_string(color=input$color) 

    if (input$shape != 'None') 
    p <- p + aes_string(shape=input$shape) 

    facets <- paste(input$facet_row, '~', input$facet_col) 

    if (facets != '. ~ .') 
    p <- p + facet_grid(facets) 

    if (input$jitter) 
    p <- p + geom_jitter() 

    if (input$smooth) 
    p <- p + geom_smooth() 


    print(p) 

}) 


}) 
相關問題