r语言 - RShiny - 如何使用多个输入(例如,从"selectInput"中选择一个或多个国家,然后确定输出到折线图)



从下面的代码中,我希望用户能够选择一个或多个国家,然后确定图形的输出。

我的原始数据来源是:

data_1 <- read.csv("C:/Users/Owner/Downloads/Activity.csv")
df <- data.frame(data_1$REPORT_DATE,data_1$PEOPLE_D_NEW_COUNT,
data_1$PEOPLE_P_NEW_CASES_COUNT,data_1$PEOPLE_D_COUNT,data_1$PEOPLE_P_CASES_COUNT,data_1$COUNTRY_SHORT_NAME)

下面的这段代码似乎还可以

selectInput(inputId = "country", label = "Country: ", multiple = TRUE,
choices = sort(unique(df$COUNTRY_SHORT_NAME)))

我真正纠结的一点是如何在服务器端编码,即绘图输出取决于从selectInput中选择的国家,即按日期和一个或多个国家的折线图。

如果我也能为图形选择所需的数据源,例如df$PEOPLE_p_NEW_CASES_COUNT或df$PEOPLE_D_COUNT等,那也会很好。

应用程序代码

library(shiny)
library(dplyr)
library(dygraphs)
library(xts)
library(RColorBrewer)
library(plotly)
library(DT)
library(highcharter)
library(shinyWidgets)
library(shinydashboard)
library(shinydashboardPlus)
library(ggplot2)
covid_1 <-
read.csv("C:/Users/Owner/Downloads/COVID-19 Activity.csv")
df <-
data.frame(
covid_1$REPORT_DATE,
covid_1$PEOPLE_DEATH_NEW_COUNT,
covid_1$PEOPLE_POSITIVE_NEW_CASES_COUNT,
covid_1$PEOPLE_DEATH_COUNT,
covid_1$PEOPLE_POSITIVE_CASES_COUNT,
covid_1$COUNTRY_SHORT_NAME
)
worldmap <- df %>%
group_by(covid_1.COUNTRY_SHORT_NAME, covid_1$COUNTRY_ALPHA_3_CODE) %>%
summarise_at(vars(covid_1.PEOPLE_DEATH_NEW_COUNT),
list(deaths = sum))
ui <-
dashboardPage(
dashboardHeader(titleWidth = 350, title = "COVID19 - UK & World Data"),
dashboardSidebar(width = 350,
sidebarMenu(
menuItem("World Map", tabName = "dashboard", icon = icon("dashboard")),
menuItem(
"Line Graph by Selection",
tabName = "multiselect",
icon = icon("dashboard")
)
)),
dashboardBody(tabItems(
# First tab content
tabItem(tabName = "dashboard", br(),
fluidRow(column(
width = 12, plotlyOutput("World_Map", height = 600)
))),

#Second Tab
tabItem(
tabName = "multiselect",
br(),
column(width = 8, highchartOutput("line", height = 450)),
column(
width = 4,
selectInput(
inputId = "country",
label = "Country: ",
multiple = TRUE,
choices = sort(unique(df$covid_1.COUNTRY_SHORT_NAME))
)
)
)
))
)
server <- function(input, output) {
output$World_Map <- renderPlotly({
plot_ly(
worldmap,
type = 'choropleth',
locations = worldmap$`covid_1$COUNTRY_ALPHA_3_CODE`,
z = worldmap$deaths,
text = worldmap$COUNTRY_SHORT_NAME,
colorscale = "Reds"
) %>% layout(title = "<b><b>")
})

# THIS IS WHERE I WANT OUTPUT LINE GRAPH
#
#  Best scenario is whereby I would like a line graph where lines are represented by countries selected from Second Tab and by date df$REPORT_DATE)
#  the data could be one of (covid_1$PEOPLE_DEATH_NEW_COUNT,covid_1$PEOPLE_POSITIVE_NEW_CASES_COUNT,covid_1$PEOPLE_DEATH_COUNT,
#  covid_1$PEOPLE_POSITIVE_CASES_COUNT)

}
shinyApp(ui = ui, server = server)

您可以使用df的反应版本,每次用户从selectInput中选择一个国家时,该版本都会根据国家/地区进行过滤。

这部分进入你的服务器功能

df_reactive<-反应性({
req(输入$country(
df<-df%>%筛选器(%input$COUNTRY中的COUNTRY_SHORT_NAME%(})

然后可以使用df_reactive((而不是df来使用反应性df。

为了能够在地图上动态选择要渲染的变量,您可以考虑使用一些radioButtons文档,并以与上述类似的方式使用。

相关内容

最新更新