Ошибка time_trans работает с объектами класса posixct только в R - PullRequest
1 голос
/ 08 апреля 2020

Я получил Error: Invalid input: time_trans works with objects of class POSIXct only, когда я запускаю программу в блестящем. И это мой код в shiny:

library(ggplot2)
library(Cairo)   # For nicer ggplot2 output when deployed on Linux
library(shiny)

ui <- fluidPage(
  fluidRow(
    column(width = 4, class = "well",
           h4("Brush and double-click to zoom"),
           plotOutput("plot1", height = 300,
                      dblclick = "plot1_dblclick",
                      brush = brushOpts(
                        id = "plot1_brush",
                        resetOnNew = TRUE
                      ))),
             column(width = 6,
                    plotOutput("plot3", height = 300)
             )))

server <- function(input, output) {
  # -------------------------------------------------------------------
  # Single zoomable plot (on left)
  ranges <- reactiveValues(x = NULL, y = NULL)

  output$plot1 <- renderPlot({
    ggplot(sensor_online, aes(x= record_time, y= temperature)) +
      geom_point() +
      coord_cartesian(xlim = ranges$x, ylim = ranges$y, expand = FALSE)
  })

  # When a double-click happens, check if there's a brush on the plot.
  # If so, zoom to the brush bounds; if not, reset the zoom.
  observeEvent(input$plot1_dblclick, {
    brush <- input$plot1_brush
    if (!is.null(brush)) {
      ranges$x <- c(brush$xmin, brush$xmax)
      ranges$y <- c(brush$ymin, brush$ymax)

    } else {
      ranges$x <- NULL
      ranges$y <- NULL
    }})}

  # -------------------------------------------------------------------
shinyApp(ui, server)

Что я должен исправить на моем shiny сервере, чтобы не было Error?

1 Ответ

1 голос
/ 09 апреля 2020

Согласно этому ТАКому ответу, все, что вам нужно, это преобразовать range$x в Date или POSIXct. Смотрите код ниже. Я сгенерировал некоторые данные, чтобы сделать код воспроизводимым.

library(ggplot2)
library(Cairo)   # For nicer ggplot2 output when deployed on Linux
library(shiny)
library(dplyr)

ui <- fluidPage(
  fluidRow(
    column(width = 4, class = "well",
           h4("Brush and double-click to zoom"),
           plotOutput("plot1", height = 300,
                      dblclick = "plot1_dblclick",
                      brush = brushOpts(
                        id = "plot1_brush",
                        resetOnNew = TRUE
                      ))),
    column(width = 6,
           plotOutput("plot3", height = 300)
    )))

server <- function(input, output) {
  # -------------------------------------------------------------------
  # Single zoomable plot (on left)
  ranges <- reactiveValues(x = NULL, y = NULL)

  # Generate some data
  #######################################
  sensor_online <- tibble(record_time = seq.POSIXt(as.POSIXct("2017-06-20 10:00"),
                                                   as.POSIXct("2017-08-20 10:00"),
                                                   by = "1 day"),
                          temperature = sin(rnorm(62, 35, sd = 1)) / 3)

  ########################################

  output$plot1 <- renderPlot({

    # I've added this chunck
    ########################################
    if (!is.null(ranges$x)) {
      # ranges$x <- as.Date(ranges$x, origin = "1970-01-01")
      ranges$x <- as.POSIXct(ranges$x, origin = "1970-01-01")
    }
    #########################################

    ggplot(sensor_online, aes(x = record_time, y = temperature)) +
      geom_point() +
      coord_cartesian(xlim = ranges$x,
                      ylim = ranges$y,
                      expand = FALSE)
  })

  # When a double-click happens, check if there's a brush on the plot.
  # If so, zoom to the brush bounds; if not, reset the zoom.
  observeEvent(input$plot1_dblclick, {
    brush <- input$plot1_brush
    if (!is.null(brush)) {

      ranges$x <- c(brush$xmin, brush$xmax)

      ranges$y <- c(brush$ymin, brush$ymax)

    } else {
      ranges$x <- NULL

      ranges$y <- NULL
    }})}

# -------------------------------------------------------------------
shinyApp(ui, server)

А вот и вывод.

enter image description here


Рассмотрите возможность использования dygraphs для создания интерактивных графиков временных рядов. Вы можете прочитать об этом здесь

library(shiny)
library(dygraphs)
library(xts)
library(dplyr)


ui <- shinyUI(fluidPage(

    mainPanel(
      dygraphOutput("dygraph")
    )
))

server <- shinyServer(function(input, output) {

  sensor_online <- tibble(record_time = seq.POSIXt(as.POSIXct("2017-06-20 10:00"),
                                                   as.POSIXct("2017-08-20 10:00"),
                                                   by = "1 day"),
                          temperature = sin(rnorm(62, 35, sd = 1)) / 3)

  sensor_online <- xts(x = sensor_online$temperature, order.by = sensor_online$record_time)

  output$dygraph <- renderDygraph({
    dygraph(sensor_online)
  })

})


shinyApp(ui, server)

enter image description here

...