我打算对此数据框进行交互式Shiny ggplot:
key
我想创建一个交互式图形,其中X轴表示数据。
但是,我希望它可以通过以下方式进行交互:
我知道我的代码有很多错误:
visits <- structure(list(date = structure(c(17000, 17001, 17002, 17003,
17004, 17005, 17006, 17007, 17008, 17009, 17010, 17011, 17012,
17013, 17014, 17015, 17016, 17017, 17018, 17019, 17020, 17021,
17022, 17023, 17024, 17025, 17026, 17027, 17028, 17029, 17030,
17031, 17032, 17033, 17034, 17035, 17036, 17037, 17038, 17039,
17040, 17041, 17042, 17043, 17044, 17045, 17046, 17047, 17048,
17049, 17050, 17051, 17052, 17053, 17054, 17055, 17056, 17057,
17058, 17059, 17060, 17061, 17062, 17063, 17064, 17065, 17066,
17067, 17068, 17069, 17070, 17071, 17072, 17073, 17074, 17075,
17076, 17077, 17078, 17079, 17080, 17081, 17082, 17083, 17084,
17085, 17086, 17087, 17088, 17089, 17090, 17091, 17092, 17093,
17094, 17095, 17096, 17097, 17098, 17099, 17100), class = "Date"),
visits = c(64, 118, 86, 90, 59, 53, 31, 62, 66, 1161, 719,
209, 944, 610, 197, 136, 110, 106, 232, 145, 100, 105, 121,
85, 137, 91, 139, 83, 73, 91, 81, 85, 74, 65, 80, 732, 337,
144, 113, 107, 76, 126, 127, 125, 264, 181, 118, 61, 113,
119, 101, 261, 122, 89, 693, 603, 392, 129, 120, 136, 84,
72, 74, 133, 104, 93, 83, 244, 210, 103, 108, 109, 111, 72,
74, 88, 77, 90, 84, 86, 90, 79, 65, 81, 199, 134, 93, 177,
207, 88, 75, 283, 721, 544, 403, 235, 116, 118, 161, 280,
186)), .Names = c("date", "visits"), row.names = 200:300, class = "data.frame")
如果我没有使用inputPanel(
selectInput("visits", label = "Dates",
choices = c("Days", "Weeks", "Months", "Years"), selected = Days)
)
renderPlot({
ggplot(visits, aes(x = date, y = visits)) +
geom_point(size=0.2) +
geom_line(lwd=0.1)
})
,我会看到ggplot。因此,我的问题是如何使其与上面所需的选项进行交互。
答案 0 :(得分:0)
我们可以根据用户输入的内容进行分组,然后在aes_string
中使用ggplot
接受x和y作为字符串。
library(shiny)
library(dplyr)
library(lubridate)
#Load Visits
ui <- fluidPage(
inputPanel(
selectInput("visits", label = "Dates",
choices = c("Days", "Weeks", "Months", "Years"), selected = 'Days')
),
mainPanel(plotOutput('plt'))
)
server <- function(input, output, session) {
df <- reactive({
if(input$visits=='Days'){
visits_final <- visits %>% group_by(Days = date)
}else if(input$visits=='Weeks'){
visits_final <- visits %>% group_by(Weeks = week(date))
} else if(input$visits=='Months'){
visits_final <- visits %>% group_by(Months = month(date))
} else if(input$visits=='Years'){
visits_final <- visits %>% group_by(Years = year(date))
}
visits_final <- visits_final %>% summarise(Visits=sum(visits, na.rm = TRUE))
})
#TO check your df befor ploting
observe(print(df()))
output$plt <- renderPlot({
ggplot(df(), aes_string(x =input$visits, y = "Visits")) +
geom_point() +
geom_line(lwd=0.1)
})
}
shinyApp(ui, server)