无法使用R Shiny绘制堆积的条形图

时间:2019-01-22 12:28:37

标签: r ggplot2 shiny shinydashboard shiny-server

我是R Shiny的新手。实际上,我已经在我的Stacked Barplot中绘制了ggplot R代码。我想使用闪亮绘制相同的内容。下面是我的R代码:

ggplot(data = df, aes(x = OutPut, y = Group, fill = Group)) + 
  geom_bar(stat = "identity") + 
  facet_grid(~ Environment)

在我的R代码中,它给出正确的结果。但是我试图绘制shiny。下面是我闪亮的R代码。

ui <- fluidPage(theme = shinytheme("lumen"),
                titlePanel("Data Analysis"),
                selectInput("variable", "Variable:", c("OutPut", "Member", "Levels")),
                mainPanel(plotOutput("plot")))

# Define server function
server <- function(input, output){
  x = ggplot(data = df, aes(x = variable.names(), y = Group, fill = Group)) + 
    geom_bar(stat = "identity") + 
    facet_grid(~ Environment)
  plot(x)
}

# Create Shiny object
shinyApp(ui = ui, server = server)

它引发了错误,在这里我创建了一个下拉框,其中所有变量都已存储。因此,当我选择一个变量时,应绘制Stacked barplot。谁能帮我。

1 个答案:

答案 0 :(得分:0)

就像注释中提到的那样,您需要使用渲染功能并将其实际分配给输出以获取所需的输出。

我相信在rshiny中使用图的示例会有所帮助,因为在注释中添加它没有意义,这里是:

library(shiny)
library(ggplot2)
ui <- fluidPage(titlePanel("Fast Example with mtcars"),
                # inputs
                selectInput("x", "Choose x:", choices = names(mtcars), selected = 'mpg'),
                selectInput("y", "Choose y:", choices = names(mtcars), selected = 'hp'),
                selectInput("fill", "Choose fill:", choices = names(mtcars), selected = 'carb'),

                mainPanel(
                  #outputs
                  h2("Chosen variables are:"),
                  h4(textOutput("vars")),
                  plotOutput("plot")))


server <- function(input, output) {
  df <- mtcars

# here's how you would use the rendering functions 
# notice that I used aes_string   
  output$plot <- renderPlot({
    ggplot(data=df, 
           aes_string(x= input$x, y= input$y, fill=input$fill)) + 
      geom_point()
  })

  output$vars <- renderText(paste0('x: ', input$x, " , ", 
                                   'y: ', input$y, " , ", 
                                   'fill: ', input$fill))

}

shinyApp(ui = ui, server = server)

Rshiny教程非常有用,您可以在这里https://shiny.rstudio.com/tutorial/

进行查看。