无法在我闪亮的应用程序中使用反应元素

时间:2015-03-25 09:08:23

标签: r ggplot2 shiny

在我的闪亮应用程序中,我想更改我想要构建的ggplot barChart。 selectinput应允许更改月份(请参阅下面的数据集),因此我的绘图应相应更改。

问题:问题是,我无法在ggplot函数中使用我的反应函数甚至只是简单的input$monthid

数据集:

Month  Orders
1   Feb  984524
2   Jan 1151303
3   Mar  575000

> dput(b)
structure(list(Month = c("Feb", "Jan", "Mar"), Orders = c(984524L, 
1151303L, 575000L)), .Names = c("Month", "Orders"), class = "data.frame", row.names = c(NA, 
-3L))

ui.R

library(shiny)
library(shinythemes)

b<-read.csv("b.csv",header=TRUE,sep=",",stringsAsFactors=TRUE)

shinyUI(fluidPage(theme= shinytheme("flatly"),

  sidebarLayout(   
    sidebarPanel(
    selectInput(inputId = "monthid", label = "Month",choices = b$Month,selected = b$Month[1])),
    mainPanel(plotOutput("plot"))    

      ))
  )

server.R

library(shiny)
library(shinythemes)
library(ggplot2)
    b<-read.csv("b.csv",header=TRUE,sep=",",stringsAsFactors=TRUE)

shinyServer(function(input, output) {


  #making a reactive object
  m<-reactive ({

    as.character(input$monthid)

    })


    output$plot<- renderPlot({

    #probably I am making a subset error in x inside aes parameter  
    ggplot(data = b, aes(x = b[,m()] ,y = b$Orders)) + geom_bar(stat="identity")

    })
})

1 个答案:

答案 0 :(得分:1)

这是一个最小的工作示例,您可以在会话中复制并粘贴以运行,但是带有单个条形图的条形图实际上没有多大意义(如果您问我,看起来很难看):

library(shiny)

shinyApp(
  ui = fluidPage(
    sidebarLayout(   
      sidebarPanel(
        selectInput(
          inputId = "monthid", 
          label = "Month",
          choices = b$Month,
          selected = b$Month[1]
        )
      ),
      mainPanel(plotOutput("plot"))
    )
  ), 
  server = function(input, output) {
    DF <- reactive({
      b[b$Month == input$monthid, , drop = FALSE]
    })
    output$plot <- renderPlot({
      ggplot(DF(), aes(x = Month, y = Orders)) + 
        geom_bar(stat = "identity")
    })
  }
)

看起来有点像这样:

由于这看起来不太好IMO,你可以通过突出显示当前选中的栏来做某事,例如:

b$highlight <- factor("Not Selected", levels = c("Not selected", "Selected"))

shinyApp(
  ui = fluidPage(
    sidebarLayout(   
      sidebarPanel(
        selectInput(
          inputId = "monthid", 
          label = "Month",
          choices = b$Month,
          selected = b$Month[1]
          )
        ),
      mainPanel(plotOutput("plot"))
      )
    ), 
  server = function(input, output) {
    DF <- reactive({
      b[b$Month == input$monthid, "highlight"] <- "Selected"
      b
    })
    output$plot <- renderPlot({
       ggplot(DF(), aes(x = Month, y = Orders, fill = highlight)) + 
         geom_bar(stat = "identity")
    })
  }
)

这看起来如下: