[英]Reactive plots in shiny with multiple datasets
I'm trying to produce a reactive UI in shiny. 我正在尝试生成闪亮的反应式UI。
I have a dataset consisting in supermarket products daily sales over a period of 2 years. 我有一个数据集,其中包含两年内超市产品的每日销售额。 For instance:
例如:
product Total_Sales Date(YYYY-MM-DD)
1. 'Coke 0.5 L' 23 2014-01-02
2. 'Sprite 0.5 L' 18 2014-01-02
3. 'CornFlakes 1.kg' 21 2014-01-02
4. 'Coke 0.5 L' 25 2014-01-03
5. 'BurgersX6 1.kg' 8 2014-01-03
6. 'CornFlakes 1.kg' 17 2014-01-03
I want my user to select a product as input and, given the input, plot the corresponding time_series. 我希望我的用户选择一种产品作为输入,并在给出输入的情况下绘制相应的time_series。
selectInput("product", "Choose a product:",
choices = as.factor(levels(df$product)))
And this works fine. 这很好。
In server: 在服务器中:
datasetInput <- df
output$tsplot <- reactive({renderPlot(
{dataset <- datasetInput[product==input$product,]
plot(as.ts(dataset$Total_Sales,dataset$Date),start=input$start,end=input$end")
}
)
})
Unfortunately I don't get any plot out. 不幸的是我没有积蓄。 If instead I put a reactive input datasetInput <- df[product==input$product,] and change the output$tsplot accordingly I get as an output the first available input, but when I change the input$product the plot remains the same.
相反,如果我放了一个反应性输入datasetInput <-df [product == input $ product,]并相应地更改了output $ tsplot,则我得到了第一个可用输入作为输出,但是当我更改input $ product时,该图保持不变。 I'm pretty new to shiny, any help is much welcomed, thank you
我刚刚接触到光泽,欢迎您的帮助,谢谢
Try to filter your input dataframe in a reactive
expression and then call the result in renderPlot
: 尝试以
reactive
表达式过滤输入数据帧,然后在renderPlot
调用结果:
datasetInput <- reactive({
df[df$product == input$product, ]
})
output$tsplot <- renderPlot({
dataset <- datasetInput()
plot(as.ts(dataset$Total_Sales, dataset$Date, start = input$start, end = input$end))
})
EDIT : 编辑:
With your data : 根据您的数据:
df <- read.table(
text = " Name Total_Sales Date
1. 'Coke 0.5 L' 23 2014-01-02
2. 'Sprite 0.5 L' 18 2014-01-02
3. 'CornFlakes 1.kg' 21 2014-01-02
4. 'Coke 0.5 L' 25 2014-01-03
5. 'BurgersX6 1.kg' 8 2014-01-03
6. 'CornFlakes 1.kg' 17 2014-01-03"
)
df$Date <- as.Date(as.character(df$Date, format = "%Y-%m-%d"))
library("shiny")
ui <- fluidPage(
selectInput("product", "Choose a product:",
choices = levels(df$Name)),
plotOutput(outputId = "tsplot")
)
server <- function(input, output){
datasetInput <- reactive({
df[df$Name == input$product, ]
})
output$tsplot <- renderPlot({
dataset <- datasetInput()
plot(as.ts(dataset$Total_Sales, dataset$Date))
})
}
shinyApp(ui = ui, server = server)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.