使用ggplot进行闪亮的反应数据绘图

时间:2020-08-04 21:17:24

标签: r ggplot2 shiny dataset reactive

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

基本上,用户必须使用一个单选按钮和一个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)的方法,因为 x < / strong>和 y 会有所不同,具体取决于用户输入。

任何想法如何处理此案?

谢谢

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情。

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

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

答案 1 :(得分:0)

谢谢您找到了解决方案。 我在if语句中包装了yof aes()函数:

p1 <- ggplot(data = data_intacc(), 
{if (input$ind_access == "reason_access" & input$dissag_access == "age_access") {
aes(x=value_1, y=value_2, fill= Total)
}}
{if (input$ind_access == "reason_access" & input$dissag_access == "gender_access") {
aes(x=value_3, y=value_4, fill= Total)
}}
)
+geom_bar(stat= "identity")
print(p1)