我正在尝试找出如何使 ggplot 输出对我 Shiny 应用程序的 UI 中的 varSelectInput 函数作出 react 。例如,我希望能够选择两个不同的变量并将它们绘制为彼此的函数。我在这个例子中使用了航类数据集,即选择 arr_time 和 dep_delay 并查看 x 轴上的 arr_time 和 y 轴上的 dep_delay。
DateRangeInput 目前没有功能,但我最终希望能够按月筛选出在 ggplot 输出中绘制的结果。
library(tidyverse)
library(shiny)
flights <- nycflights13::flights
# Define UI for application
ui <- navbarPage(
"NYC Flights",
tabPanel(
"Flights",
sidebarPanel(
h4("Flight Inputs"),
selectInput(
"Airline_Select",
label = "Select Airline",
choices = flights$Carrier,
selected = TRUE
),
dateRangeInput(
"dates",
label = "Dates",
start = min(flights$Month),
end = max(flights$Month),
min = min(flights$Month),
max = max(flights$Month)
),
varSelectInput(
"X_Axis",
label = "Select Variable 1",
data = flights
),
varSelectInput(
"Y_Axis",
label = "Select Variable 2",
data = flights
),
),
)
)
mainPanel(plotOutput("flights_plot"))
# Define server logic
server <- function(input, output) {
output$flights_plot <- renderPlot({
ggplot(data = flights, aes(x = input$X_Axis, y = input$Y_Axis)) + geom_point()
})
}
# Run the application
shinyApp(ui = ui, server = server)
最佳答案
欢迎来到 stackoverlfow。
为了拥有一个功能性的应用程序,您必须更改一些内容。我在这里总结了我所看到的事情,并将代码中的详细信息作为注释。
- 准备好你的数据,你应该考虑创建变量
- 不要将具有重复值的整个向量作为
choices
参数放入selectInput
中,您应该传递不同的选项。 - 最好尽可能选择一个值。这样一来,您的应用将在启动时默认显示一些内容。
- 使用输入来过滤数据。
selectInput
创建一个字符串值,为此,您应该在 ggplotmapping
参数中使用aes_string
。
library(shiny)
library(tidyverse)
# You have to Adequate your data: You have to create a dete variable
# in order to make the `dateRangeInput` work. You can do that using
# `year`, `month` and `day` variables as follow.
flights <- nycflights13::flights %>%
mutate(
date = as.Date(paste(year, month, day, sep = "-"))
)
ui <- navbarPage(
title = "NYC Flights",
tabPanel(
title = "Flights",
sidebarPanel(
h4("Flight Inputs"),
# The choices argument should be the unique
# list of arilines, not the whole vector with
# duplicates
selectInput(
"airline",
label = "Select Airline",
choices = unique(flights$carrier),
selected = 'UA' # It is a good idea to select a value
# visible when you launch the app
),
dateRangeInput(
"dates",
label = "Dates",
start = min(flights$date),
end = max(flights$date)
),
varSelectInput(
"X_Axis",
label = "Select Variable 1",
data = flights,
selected = "date" # selecting one
),
varSelectInput(
"Y_Axis",
label = "Select Variable 2",
data = flights,
selected = "dep_delay" # selecting one
)
),
mainPanel(
plotOutput("plot")
)
)
)
server <- function(input, output, session) {
output$plot <- renderPlot({
flights %>%
# Use your inputs to filter the data
filter(date >= input$dates[1], date <= input$dates[2], carrier == input$airline) %>%
# since the selectImput create a character element, you should use
# ase_string() to map the x an y variables
ggplot(aes_string(x = input$X_Axis, y = input$Y_Axis)) +
geom_point()
})
}
shinyApp(ui, server)
关于R Shiny ggplot 对 varSelectInput 有反应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61625109/