Как выполнить реактивную функцию набора данных в Shiny - график R - PullRequest
1 голос
/ 24 февраля 2020

Как выполнить реактивную функцию набора данных в Shiny - линейный график Особенно не понимаю, как применить набор данных в reactive() функцию, чтобы реагировать на выбранный вход

# sample data
df <- economics %>%
  select(date, psavert, uempmed) %>%
  gather(key = "variable", value = "value", -date) %>%
  as.data.table()

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

  # Application title
  titlePanel("Football Analysis"),

  sidebarLayout(
    sidebarPanel(
      selectizeInput("variable_names", "Names of Variable", choices = unique(df$variable), selected = unique(df$variable)[1])
    ),

    mainPanel(
      highchartOutput("plot")
    )
  )
)

server <- function(input, output) {

  reactivedf <- reactive({ df[variable == input$variable_names,]
  })

  output$plot <- renderHighchart({
    df %>%
       hchart('line',hcaes(x = reactivedf()$date,y = reactivedf()$value))
  })
}

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

Моя цель просто выбрать 1 тип серии , а затем , как этот тип с линейным графиком , в целях изучения использования блеска. Я не могу понять, как подать заявку в обычном ggplot.

ggplot(df, aes(x = date, y = value)) + 
  geom_line(aes(color = variable), size = 1) +
  scale_color_manual(values = c("#00AFBB", "#E7B800")) +
  theme_minimal()

1 Ответ

2 голосов
/ 24 февраля 2020

Это должно приблизить вас

# load packages
library(shiny)
library(highcharter)
library(ggplot2)
library(dplyr)
library(tidyr)
library(data.table)

# sample data
df <- economics %>%
  select(date, psavert, uempmed) %>%
  gather(key = "variable", value = "value", -date) %>%
  as.data.table()

# define color mapping
color_mapping <- c("psavert" = "#00AFBB", "uempmed" = "#E7B800")

# Define UI for application that draws a histogram
ui <- fluidPage(
  # Application title
  titlePanel("Football Analysis"),

  sidebarLayout(
    sidebarPanel(
      selectizeInput(inputId = "variable_names", 
                     label = "Names of Variable", 
                     choices = unique(df$variable), 
                     selected = unique(df$variable)[1])
    ),

    mainPanel(
      # use plotOutput for ggplot
      plotOutput("plot")
    )
  )

)

server <- function(input, output, session) {

  # use renderPlot for ggplot
  output$plot <- renderPlot({
    df %>% 
      # you can use the input like a regular string
      filter(variable == input$variable_names) %>% 
      ggplot(aes(x = date, y = value)) + 
      geom_line(aes(color = variable), size = 1) +
      # show different colors for different values
      scale_color_manual(values = color_mapping[input$variable_names]) +
      theme_minimal()   
  })
}

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