这是我第一次构建应用程序,我想知道代码中缺少的函数或参数是什么。我想显示一个普通的条形图,该条形图可以动态过滤我希望看到的“公司”,绩效变量(例如“利润”)和日期范围。
我相信我的错误是由于shiny
调用中的不精确性造成的,因为我想要的非常简单。您可以通过运行以下代码来获得它(但shiny
提供的交互作用是不可能的):
library(ggplot2)
sample_data = data.frame(Company_Name=c("Company 1","Company 2","Company 3",
"Company 1","Company 2","Company 3",
"Company 1","Company 2","Company 3"),
Profits_MM = c(20,100,80,
45,120,70,
50,110,90),
Sales_MM = c(200,800,520,
300,1000,630,
410,1150,770),
Year=c(2016,2016,2016,
2017,2017,2017,
2018,2018,2018))
ggplot(data = sample_data, aes(x=Year, y = Profits_MM,
fill=as.factor(Company_Name))) + geom_col(position="dodge")
但是我只提到它,因此可能会对我想要的输出有所了解。我设置的代码实际上是以下代码:
rm(list=ls()); gc()
library(shiny)
library(ggplot2)
library(dplyr)
sample_data = data.frame(Company_Name=c("Company 1","Company 2","Company 3",
"Company 1","Company 2","Company 3",
"Company 1","Company 2","Company 3"),
Profits_MM = c(20,100,80,
45,120,70,
50,110,90),
Sales_MM = c(200,800,520,
300,1000,630,
410,1150,770),
Year=c(2016,2016,2016,
2017,2017,2017,
2018,2018,2018))
# UI
ui <- fluidPage(
sidebarLayout(
# Input(s)
sidebarPanel(
checkboxGroupInput(inputId = "sel_com",
label = "Company Selection:",
choices = c("Company 1","Company 2","Company 3"),
selected = "Company 1"),
selectInput(inputId = "y",
label = "Performance Variable",
choices = c("Profits (in Millions)" = "Profits_MM",
"Sales (in Millions)" = "Sales_MM"),
selected = "Profits_MM"),
sliderInput("year","Year Selection:",
min=2016,
max=2018,
value=c(2017,2018),
step=1)
),
# Output(s)
mainPanel(
plotOutput(outputId = "barplot")
)
)
)
# Server
server <- function(input, output, session) {
companies_sel <- reactive({
req(input$sel_com)
filter(sample_data, Company_Name %in% input$sel_com)
})
year_sample <- reactive({
req(input$year)
if(length(input$year)>1){
Years = seq(input$year[1],input$year[2])
filter(companies_sel(), Year %in% Years)
}
if(length(input$year==1)){
filter(companies_sel(), Year %in% input$year)
}
})
output$barplot <- renderPlot({
ggplot(data = year_sample(), aes_string(x=input$year, y = input$y, fill=as.factor(input$sel_com))) +
geom_col(position="dodge")
})
}
shinyApp(ui = ui, server = server)
我能够获得一些输出,但一次只能获得一家公司,并且不会更改范围大小。也许我不理解observeEvent
函数的使用,这可能在其中起作用。那么,如何使inputSlider
和其他选项与ggplot2
图充分交互?
这里是ouptut错误的一个示例: