从下拉列表中选择一个变量,并将其作为参数传递给R Shiny中的reactivePlot

时间:2013-07-14 01:16:19

标签: r shiny

我有一个关于R Shiny应用程序的一般问题:我有一个ID列表,最终用户可以在下拉菜单中选择(selectInput),我希望根据这个ID。换句话说,所选变量将作为参数传递给绘图函数,每次我选择不同的ID时,绘图也会更改。我能否知道这在Shiny中是否可行?我很感激,如果有人能提供类似问题的工作实例。谢谢!

1 个答案:

答案 0 :(得分:14)

以下是一个示例工作示例,其中包含dropdown作为参数。可以在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)

})


})