我正在尝试构建一个闪亮的Web应用程序,以允许不同的用户输入,然后相应地绘制图形/输出数据表。我使用的是世界卫生组织有关自杀率的数据,我想做一些图: 1.直方图,y =自杀_否,x =年龄组,中性(男女混合)样本=世界或一个国家(如果选择一个国家,则创建数据的子集)。到目前为止,我分别进行了渲染,因为在需要全局数据时无需指定国家/地区,否则我将使用input $ country作为填充 2.直方图y = suicide_no,x =年龄组,性别特定(男女分别,每个年龄组两个横条),样本=世界或其中一个国家。我将其分别呈现给中性,因为针对特定性别,我包括fill = gender。 3.线图y = suicide_no,x =年,性别中立,样本=世界或一个/几个国家 4.线图y = suicide_no,x =年,性别特定,sample =世界或仅一个国家(两条线代表男性和女性)
这是我的代码:
library(shiny)
library(ggplot2)
setwd("C:\\Users\\Lenovoi7\\Shrewsbury School\\IT\\Coursework")
who<-data.frame(read.csv("who.csv", stringsAsFactors = TRUE))
countries <- sort(unique(who$country))
countries<-union(countries, c("World"))
ui<-fluidPage(
sidebarLayout(
sidebarPanel(
#Allow user to choose the variable which should be plotted on the x axis
selectInput(
"x", "Please choose the x variable",
c("",
"Year" = "year",
"Age group" = "age")),
#only show this panel when the x variable is chosen
conditionalPanel(
condition = "input.x == 'age' || input.x == 'year'",
selectInput(
inputId = "gender",
label = "Please specify the gender characteristics",
choices = c("", "Gender neutral" = "gender_neutral",
"Gender specific" = "gender_specific"),
selected = NULL),
#only show this panel if the input is gender_specific
conditionalPanel(
condition = "input.gender == 'gender_specific'",
selectInput(
inputId = "country",
label = "Select a country:",
choices = countries,
selected = "Bosnia and Herzegovina")),
conditionalPanel(
condition = "input.gender == 'gender_neutral'",
selectInput(
inputId = "country",
label = "Select a country:",
choices = countries,
selected = "Bosnia and Herzegovina")))),
mainPanel(
conditionalPanel(
condition = 'input.x=="age" & input.gender=="gender_neutral" & input.country=="world"',
plotOutput("hgnw")),
conditionalPanel(
#any one country
condition = 'input.x=="year" & input.gender=="gender_neutral"& input.country==input$country',
plotOutput("lgnw")
))))
server <- function(input, output) {
#render the plot when x=age, gender=gender_neutral, sample=world
output$hgnw<-renderPlot({
validate(need(input$x=="age" & input$gender=="gender_neutral"))
ggplot(data=who, aes(x=age)) + geom_bar(aes(weights=suicides_no))
})
#render the plot when x=year, gender=gender_neutral, sample=world
output$lgnw <- renderPlot({
validate(need(input$x=="year", message=FALSE))
ggplot(data=who, aes(x=year)) + geom_line(aes(y=suicides_no)) + geom_point(aes(y=suicides_no))
})
}
shinyApp(ui = ui, server = server)
我创建了一些(不是全部)条件面板和绘图输出,然后尝试测试在主面板中调用时在服务器中计算出的绘图是否正常工作(不同的绘图取决于我尝试输入的用户输入使用验证功能来完成),但事实并非如此。我想知道如何在服务器和主面板中解决此问题。我是否使用if语句或条件面板?这目前不起作用,甚至可能不是解决我的问题的好方法。任何帮助是极大的赞赏。