首页 > 解决方案 > 使用 ggplot 绘制闪亮的反应数据

问题描述

我正在创建一个闪亮的应用程序,包括绘制来自不同数据集的数据。

基本上,用户必须使用一个单选按钮和一个 selectinput 选择两次才能获得所需的情节。这是一个最小的例子:

#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

# create data
name <- c("Jon", "Bill", "Maria")
age <- c(23, 41, 32)
d1 <- data.frame(name, age)
employee <- c('John Doe','Peter Gynn','Jolie Hope')
salary <- c(21000, 23400, 26800)
startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14'))
d2 <- data.frame(employee, salary, startdate)
library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Old Faithful Geyser Data"),

    # Sidebar with a slider input for number of bins 
    sidebarLayout(
        sidebarPanel(
            radioButtons("ind1", "Choose indicator:",
                         c("Q1" = "q1",
                           "Q2" = "q2")
                         
            )
        ),

        # Show a plot of the generated distribution
        mainPanel(
            selectInput("ind2", "Choose metrics:",
                        c("M1" = "m1",
                          "M2" = "m2"),
            plotOutput("gmplot"))
    
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    # Create a "data_source" reactive variable
    data_intacc <- reactive({
        # Return the appropriate data source depending on
        # the chosen radio button
        if (input$ind1 == "q1" & input$ind2 == "m1") {
            data <- d1
        } else if (input$ind1 == "q2" & input$ind2 == "m2") {
            data <- d2
        } 
        return(data)
    })
    
    
    output$gmplot <-renderPlot({
        data = data_intacc()
        p1 <- ggplot(data, aes(x, y, fill)) +geom_bar(stat= "identity")
        print(p1)
        
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

我的问题是基于用户输入的数据是不同的,所以我需要找出一种方法来对 ggplot2 中的反应数据进行子集化以定义aes(x, y)因为xy会根据用户输入而有所不同。

知道如何处理这种情况吗?

谢谢

标签: rggplot2shinydatasetreactive

解决方案


你可以尝试这样的事情。

output$gmplot <- renderPlot({
    ggplot(data = data_intacc(), aes_string(x = input$input1, y = input$input2, fill = input$input3)) + 
      geom_bar(stat = "identity")
  })

您必须以正确的方式指定输入才能使其正常工作。如果您可以分享更多代码,也许我们可以为您提供更多帮助。


推荐阅读