我正在教自己Shiny,我被困在我的ggplot2图上,无法使用被动dateRangeInput作为我的x轴。我有几个问题:
Aesthetics must be either length 1 or the same as the data (33108): x, y
(x =输入$ date ...
library(shiny)
library(tidyr)
library(ggplot2)
tweets <- read.csv(file.choose())
colnames(tweets)[1] <- "Content"
tweets <- separate(tweets, created_at, c("Date", "Time"), sep = " ")
tweets$Date <-as.Date(tweets$Date, "%m/%d/%Y")
ui <- fluidPage(
dateRangeInput(inputId = "date",
strong("Date Range"),
start = "2009-05-04", end = "2018-02-28",
min = "2009-05-04", max ="2018-02-28" ),
plotOutput("Graph")
)
server <- function(input, output) {
output$Graph <- renderPlot({
ggplot(tweets, aes(x = input$date, y = count)) +
geom_bar(stat = "identity", position = "stack") +
#scale_y_continuous(name = "Retweet Count", limits = c(0,370000), breaks=seq(0,370000,10000)) +
theme(panel.background = element_rect(fill = "white", colour = "grey50"))
})
}
shinyApp(ui = ui, server = server)
&#13;
答案 0 :(得分:1)
对于第一个问题,您可以updateDateRangeInput
使用here。因此,您会在server
函数之外的推文中找到最小和最大日期,然后将它们传递给输入。请务必将session
添加到您的函数中:
server <- function(input, output, session) {
observe({
updateDateRangeInput(session, "date", min = myMinDate, max = myMaxDate)
})
}
答案 1 :(得分:1)
@ Pete900的回答总结了updateDateRangeInput
的使用情况,有关详细信息,请参阅闪亮文档的this part。
关于你的第二个问题:input$date
将返回长度为2的向量,第一个元素位于较低位置,第二个元素位于所选范围的上半部分。您很可能不会直接将其用作x-aesthetics,而是将数据与其进行子集化,然后绘制新的子集数据。你可以,例如写
library(dpylr) # alternatevly library(tidyverse)
newtweets <- reactive({
filter(tweets, between(date ,input$date[1], input$date[2]))
})
然后,在您的ggplot中,使用newtweets()
作为您的数据。
<强>更新强>
函数filter
和between()
(这是x的快捷方式大于...而小于......)来自包dplyr
,这非常适合处理数据帧和一组名为tidyverse
的彼此非常好玩的包的集合(见here)。
当你引用新创建的反应对象newtweets()
时,请确保不要忘记这个paranthesis,因为它现在是一个函数调用,如果输入发生变化,它会启用闪亮来更新数据帧。
<强>更新强>
我在其中创建一些人工数据的完整工作示例:
library(shiny)
library(tidyverse)
library(lubridate)
# tweets <- read.csv(file.choose())
st <- ymd("2009-05-01")
en <- ymd("2018-02-28")
dates <- seq.Date(from = st, to = en, by = 1)
tweets <- tibble(date = dates, count = rnorm(length(dates), mean = 5, sd = 3))
ui <- fluidPage(
dateRangeInput(inputId = "date",
strong("Date Range"),
start = "2009-05-04", end = "2018-02-28",
min = "2009-05-04", max ="2018-02-28" ),
plotOutput("Graph")
)
server <- function(input, output) {
newtweets <- reactive({
filter(tweets, between(date ,input$date[1], input$date[2]))
})
output$Graph <- renderPlot({
ggplot(newtweets(), aes(x = date, y = count)) +
geom_bar(stat = "identity", position = "stack") +
#scale_y_continuous(name = "Retweet Count", limits = c(0,370000), breaks=seq(0,370000,10000)) +
theme(panel.background = element_rect(fill = "white", colour = "grey50"))
})
}
shinyApp(ui = ui, server = server)