Блестящее построение реактивных данных с использованием ggplot - PullRequest
0 голосов
/ 05 августа 2020

Я создаю блестящее приложение, состоящее в построении графиков данных из разных наборов данных.

Обычно пользователь должен выбрать два раза, используя одну радиокнопку и один вход select, чтобы получить желаемый график. Вот минимальный пример:

#
# 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 и y будут разными в зависимости от ввода пользователя.

Есть идеи, как поступить с этим случаем?

Спасибо

Ответы [ 2 ]

0 голосов
/ 05 августа 2020

Спасибо, я нашел решение. Я обернул функцию yof aes () в операторе if:

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)
0 голосов
/ 05 августа 2020

Вы можете попробовать что-то вроде этого.

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

Вы должны правильно указать входные данные, чтобы это работало. Если вы поделитесь своим кодом, возможно, мы сможем вам больше помочь.

...