2015-06-02 10 views
8

Desidero impostare i limiti per l'asse x per un grafico di dati di serie temporali che presenta solo il tempo (senza date). I miei limiti sono:Impostazione dei limiti con scale_x_datetime e dati temporali

lims <- strptime(c("03:00","16:00"), format = "%H:%M") 

E le mie stampe ggplot bene, ma quando aggiungo questo per scale_x_datetime

scale_x_datetime(limits = lims) 

ottengo Error: Invalid input: time_trans works with objects of class POSIXct only

completamente riproducibile esempio per gentile concessione di How to create a time scatterplot with R?

dates <- as.POSIXct(as.Date("2011/01/01") + sample(0:365, 100, replace=TRUE)) 
times <- as.POSIXct(runif(100, 0, 24*60*60), origin="2011/01/01") 
df <- data.frame(
    dates = dates, 
    times = times 
) 

lims <- strptime(c("04:00","16:00"), format = "%H:%M") 

library(scales) 
library(ggplot2) 

ggplot(df, aes(x=dates, y=times)) + 
    geom_point() + 
    scale_y_datetime(limits = lims, breaks=date_breaks("4 hour"), labels=date_format("%H:%M")) + 
    theme(axis.text.x=element_text(angle=90)) 

risposta

9

il messaggio di errore dice che dovresti usare as.POSIXct su lims. È inoltre necessario aggiungere la data (anno, mese e giorno) in lims, perché per impostazione predefinita sarà `2015, che è off limits.

lims <- as.POSIXct(strptime(c("2011-01-01 03:00","2011-01-01 16:00"), format = "%Y-%m-%d %H:%M"))  
ggplot(df, aes(x=dates, y=times)) + 
    geom_point() + 
    scale_y_datetime(limits =lims, breaks=date_breaks("4 hour"), labels=date_format("%H:%M"))+ 
    theme(axis.text.x=element_text(angle=90)) 
+0

Questo ha funzionato ma ho dovuto modificare la data alla data di oggi. – raphael

+0

Devo ammettere che non so cosa rappresentino POSIXct e POSIXlt, ma con i dati POSIXlt NON sono POSSIBILE impostare i limiti POSIXlt. '' Errore: input non valido: time_trans funziona solo con oggetti di classe POSIXct'' Per qualche ragione, POSIXct ha funzionato, come suggerito in questa risposta. Grande suggerimento. – PatrickT

Problemi correlati