Timeline graph with ggplot2

July 7, 2012

(This article was first published on 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.


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.


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


The text is added as follows;


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


Putting some limits on the y-axis.


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


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!


You can download the script here

The post Timeline graph with ggplot2 appeared first on FishyOperations.

To leave a comment for the author, please follow the link and comment on their blog: FishyOperationsCategory Archives: r.

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

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , , ,

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)