简体   繁体   中英

Shiny nearPoints not working when X Var is POSIXct

I'm working on a little shiny app that requests stock data from Yahoo. If one clicks on the plot, the respective price / datetime row from the dataset shall be shown. But unfortunately it seems that input$plot_click does not return the correct x,y - values.

Here's the mwe:

library(shiny)
library(htmlwidgets)
library(ggplot2)
library(scales)
library(dplyr)
library(RCurl)
library(XML)
library(rvest)

server <- function(input, output, session) {
   Sys.setlocale("LC_TIME", "C")
   dataset <- data.frame()
   xml.url <- "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22YHOO%22%2C%22AAPL%22%2C%22GOOG%22%2C%22MSFT%22)&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"

   YahooObs <- function(xml.url){
      script  <- getURL(xml.url)
      doc     <- xmlParse(script)
      results <- doc %>% xml_nodes("results")
      dataset <- lapply(results, FUN=function(x){xmlToDataFrame(x, stringsAsFactors = F)})[[1]]
      dataset$LastTradePriceOnly <- as.numeric(dataset$LastTradePriceOnly)
      created <- doc %>% xml_node("query") %>% xml_attr("created")
      dataset$created <- as.POSIXct(strptime(created, format="%Y-%m-%dT%H:%M:%SZ", tz="UTC")+3600)
      return(dataset)
    }

  output$newsplot <- renderPlot({
     invalidateLater(10000, session)
     dataset <<- rbind(dataset, YahooObs(xml.url))
     p <- ggplot(data = dataset)
     p <- p + layer(mapping=aes(x=created, y=LastTradePriceOnly, color= Symbol),
               geom="point", stat="identity", position="identity")
     limit_down <- as.POSIXct(Sys.time()-input$timeslider*60)
     attributes(limit_down)$tzone <- input$timezone
     limit_up <- as.POSIXct(Sys.time())
     attributes(limit_up)$tzone <- input$timezone
     p <- p + scale_x_datetime(breaks = date_breaks("200 sec"), labels = date_format("%H:%M:%S"),
                          limits=c(min(dataset$created-1800), max(dataset$created))) +
  theme(axis.text.x = element_text(angle = 90), panel.grid.major=element_blank(), panel.grid.minor=element_blank(),
        panel.background = element_blank()) + coord_cartesian()
     print(p)
  })

    output$plot_click <- renderPrint({
       paste(str(input$plot_click))
    })

   output$newstable <- renderDataTable({
      ##Transforming the created column to numeric was a hint on stackoverflow but it didn't work out
      #dataset$created <- as.numeric(dataset$created)
      nearPoints(dataset, input$plot_click, xvar="created",yvar="LastTradeDatePrice", threshold = 100, maxpoints = 10,
           addDist = TRUE)
})} #the server

ui_2 <- shinyUI(fluidPage(
    #header
    titlePanel(tags$h1("Share Prices")),
    #horizontal line
    sidebarLayout(
       sidebarPanel(
          sliderInput("timeslider", label = "Choose Timespan in minutes", min = 1, max = 60, value = 30, step = 1),
  width=3
      ),
      mainPanel(
         tabsetPanel(type="tabs",
              tabPanel("News Plot", plotOutput("newsplot", click="plot_click"),dataTableOutput("newstable"), textOutput("plot_click")),
              tabPanel("Settings",  selectInput("timezone", label="Choose your Timezone", choices=c("UTC")))
  )
)
)))# the user interface

shinyApp(ui = ui_2, server = server) # this launches your app

Any idea?

It seems that print(p) manipulates something. Using only p solves the problem and shows the POSIXct values correctly as numeric.

p <- ggplot(data = dataset)
p <- p + layer(mapping=aes(x=created, y=LastTradePriceOnly, color= Symbol),
           geom="point", stat="identity", position="identity")limit_down <- as.POSIXct(Sys.time()-input$timeslider*60)
attributes(limit_down)$tzone <- input$timezone
limit_up <- as.POSIXct(Sys.time())
attributes(limit_up)$tzone <- input$timezone
p <- p + scale_x_datetime(breaks = date_breaks("200 sec"), labels = date_format("%H:%M:%S"),
                      limits=c(min(dataset$created-1800), max(dataset$created))) +
theme(axis.text.x = element_text(angle = 90), panel.grid.major=element_blank(), panel.grid.minor=element_blank(),
    panel.background = element_blank()) + coord_cartesian()
p

works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM