[英]How to proceed reactive function of dataset in Shiny - line chart R
如何在 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)
我的目標只是選擇一種類型的系列,然后用折線圖選擇該類型,目的是學習閃亮的用法。 我也不知道如何在普通的 ggplot 中應用。
ggplot(df, aes(x = date, y = value)) +
geom_line(aes(color = variable), size = 1) +
scale_color_manual(values = c("#00AFBB", "#E7B800")) +
theme_minimal()
這應該讓你接近
# 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.