Reputation: 931
How to proceed reactive function of dataset in Shiny - line chart
Especially don't understand how apply dataset into reactive()
function to react the selected input
# 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)
My Goal is simply to choose 1 type of series then show that type with line chart , in aim to learnt the usage of shiny. I can't figure out how to apply in normal ggplot as well.
ggplot(df, aes(x = date, y = value)) +
geom_line(aes(color = variable), size = 1) +
scale_color_manual(values = c("#00AFBB", "#E7B800")) +
theme_minimal()
Upvotes: 1
Views: 141
Reputation: 6954
This should bring you close
# 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)
Upvotes: 2