[英]using shiny dateRangeInput to set axis limits in ggplot
我正在使用R / Shiny應用程序,該應用程序使用dateRangeInput的輸出來設置ggplot2圖中的x軸限制。 使用dateRangeInput子集數據可以很好地工作,但是我無法獲得scale_x_date(或scale_x_continuous或scale_x_datetime)來識別dateRangeInput返回的日期。 我已經嘗試過使用format(),as.Date,as.POSIXct,但是還沒有遇到任何麻煩。 無論我嘗試轉換dateRangeInput的輸出,還是得到:
Invalid input: date_trans works with objects of class Date only
這是我的問題的(希望)可復制的示例:
library(shiny)
library(ggplot2)
library(dplyr)
tp_date_pressed <- as.POSIXct(c("2016-01-01", "2016-03-01"))
sigma <- c(1, 1.5)
data <- data.frame(tp_date_pressed, sigma)
ui <- fluidPage(
dateRangeInput('date',
label = 'Date Range',
start = Sys.Date() - 180,
end = Sys.Date(),
max = Sys.Date()
),
plotOutput("plot")
)
server <- function(input, output) {
subData <- reactive({
data %>%
filter(
as.Date(tp_date_pressed) >= as.Date(input$date[1]),
as.Date(tp_date_pressed) <= as.Date(input$date[2])
)
})
output$plot <- renderPlot({
ggplot(subData(), aes(tp_date_pressed, sigma)) +
geom_point() +
scale_x_date(limits = input$date)
})
}
shinyApp(ui = ui, server = server)
問題在於您的原始data
; 當ggplot需要Date對象時,使用了POSIXct。 如果您將其更改為
tp_date_pressed <- as.Date(c("2016-01-01", "2016-03-01"))
請注意,還有更多問題,因為scale_x_date期望兩個值作為限制。 確保將其更改為
scale_x_date(limits = c(input$date[1], input$date[2]))
並感謝您提供可復制的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.