**FishyOperationsCategory Archives: r**, and kindly contributed to R-bloggers)

This post shows how to create a timeline graph by using ggplot2.

Let’s start by loading the ggplot2 library.

library(ggplot2)

Next let’s create a dataset which we will use to feed the graph. In the last column (y), I create random positive values for the first three rows (which will be shown above the timeline) and random negative values for the last three rows (to be shown below the timeline).

timeset<-data.frame(year=c(1986,1995,2011,1990,1998,2010),text=c('I was born','Had a nice icecream','Spotted a dodo','First swim','Crashed my bicycle','Bought a helmet'),y=c(runif(3,.5,1),runif(3,-1,-.5)))

Now comes the tricky part, creating the graph.

plot<-ggplot(timeset,aes(x=year,y=0))

Let’s add the lines which will run from the timeline arrow to the text label.

plot<-plot+geom_segment(aes(y=0,yend=y,xend=year))

The text is added as follows;

plot<-geom_text(aes(y=ytext,label=text),size=2.5,vjust=-1)

Now to fancy it up a bit with some points at the end of the line segments;

plot<-plot+geom_point(aes(y=y))

Putting some limits on the y-axis.

scale_y_continuous(limits=c(-2,2))

As the y-values are, in this case, non-informative, let’s hide ‘em.

plot<-plot+scale_y_continuous(limits=c(-2,2))

Let’s draw the timeline arrow . I agree this, is fiddling, and these values can possibly be extracted from the x-axis.

plot<-plot+geom_hline(y=0,size=1,color='purple') #draw a vertical line plot<-plot+geom_segment(x=2011.4,xend=2012.2,y=.2,yend=0,color='purple',size=1) + geom_segment(x=2011.4,xend=2012.2,y=-.2,yend=0,color='purple',size=1) #drawing the actual arrow

Now to finish it up, let’s set some options.

plot<-plot+opts(axis.text.y =theme_blank(),title='My timeline')+ylab('')+xlab('')

Let’s have a look at the result!

print(plot)

You can download the script here

The post Timeline graph with ggplot2 appeared first on FishyOperations.

**leave a comment**for the author, please follow the link and comment on his blog:

**FishyOperationsCategory Archives: r**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...