Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot timeline in R with only date variable

Tags:

r

I would like to be able to create a timeline with the following data in R:

Label      Date 
A          7/7/2015 18:17
B          6/24/2015 10:42
C          6/23/2015 18:05
D          6/19/2015 17:35 
E          6/16/2015 15:03

Like so: ---A---B-----------C-D------E

The timeline would simply be chronological dates on a horizontal line with the difference in time between them. So far I am unable to use the ggplot2 or timeline packages since I have no numerical values.

Please help and thank you in advance!

EDIT

Code I have tried

Label <- c("A", "B", "C", "D", "E")
Date <- c("7/7/2015 18:17", "6/24/2015 10:42", "6/23/2015 18:05", "6/19/2015 17:35", "6/16/2015 15:03") 
dat <-data.frame(cbind(Label, Date))

dat$Date <- as.POSIXct(dat$Date, format="%m/%d/%Y %H:%M") 
dat$y <- 0

library(ggplot2)
ggplot(dat, aes(Date, y))+ geom_point()
like image 382
STL Avatar asked Jul 09 '15 22:07

STL


People also ask

How does R deal with dates?

Date objects are stored in R as integer values, allowing for dates to be compared and manipulated as you would a numeric vector. Logical comparisons are a simple. When referring to dates, earlier dates are “less than” later dates.


1 Answers

library(ggplot2)
library(scales) # for date formats

dat <- read.table(header=T, stringsAsFactors=F, text=
"Label      Date 
A          '7/7/2015 18:17'
B          '6/24/2015 10:42'
C          '6/23/2015 18:05'
D          '6/19/2015 17:35'
E          '6/16/2015 15:03'")

# date-time variable 
dat$Date <- as.POSIXct(dat$Date, format="%m/%d/%Y %H:%M") 

# Plot: add label - could just use geom_point if you dont want the labels
# Remove the geom_hline if you do not want the horizontal line
ggplot(dat, aes(x=Date, y=0, label=Label)) + 
     geom_text(size=5, colour="red") +
     geom_hline(y=0, alpha=0.5, linetype="dashed") +
     scale_x_datetime(breaks = date_breaks("2 days"), labels=date_format("%d-%b"))

enter image description here

EDIT Add lines from labels to x-axis

ggplot(dat, aes(x=Date, xend=Date, y=1, yend=0, label=Label)) + 
     geom_segment()+
     geom_text(size=5, colour="red", vjust=0) +
     ylim(c(0,2)) +
     scale_x_datetime(breaks = date_breaks("2 days"), labels=date_format("%d-%b")) +
     theme(axis.text.y = element_blank(),
           axis.ticks.y=element_blank())

enter image description here

like image 135
user20650 Avatar answered Sep 19 '22 23:09

user20650