Thursday, July 7, 2011

R - add a table to a plot


  • suppose you have a vector with different dates of events and you want to investigates if there are month with more or less events, the first step maybe is to draw a barplot
  • so let us generate first a vector with the different dates:
  • and than we create a vector with the extracted month (as factor)
my.dat <- as.Date(, 1000, replace=T), origin="2000-01-01") 
# extract month, use the abbreviated form of months
my.months <- months(my.dat, abbreviate=T)
df <- data.frame(date=my.dat, month=my.months)
Apr Aug Dez Feb Jan Jul Jun Mai Mär Nov Okt Sep 
122  72  66 103 121  61  51  85 129  59  64  67
  • as one can see the month are in alphabetical order so we have to correct this
  • therefore we use ISOdatetime and format for creating a vector of the 12 months in the correct order and use this vector for creating a labeled factor out of df$month
df$month <- factor(df$month, levels=format(ISOdatetime(2000,1:12,1,0,0,0),"%b"))
# show the first 50 elements of my.
Jan Feb Mär Apr Mai Jun Jul Aug Sep Okt Nov Dez 
121 103 129 122  85  51  61  72  67  64  59  66
  • now we can create hour barplot (use the package plotrix)
# if it is not installed yet, install it via install.packages("plotrix")
# load the package

# create the table for plotting (the same as above)
my.table <- with(df, table(month)) # equivalent to table(df$month)
# plot it! (choosing the color from here)

barp(my.table, col=colors()[c(462:471,473,477)], xlab="Month", ylab="count")

  • now we create the same plot but add the table
# create the table for the plot - i want the horizontal table so i have to transpose it
m2 <- t(as.matrix(my.table)) 
# barplot
barp(my.table, col=colors()[c(462:471,473,477)], xlab="month", ylab="count")
# add the table: the first two arguments are the position relative to the coord system of the plot
# the third argument is the table (a data frame or a matrix), the bty: "o" draw a box, "n" no box
# bg is the argument for the background 
addtable2plot(3,140,m2, bty="o", bg="aliceblue")

now add the table with ggplot2

# generate random dates
my.dat <- as.Date(, 1000, replace=T), origin="2000-01-01") 
# extract month
my.months <- factor(month(my.dat),levels=1:12,
df <- data.frame(date=my.dat, month=my.months)

# prepare table
mytable <- tableGrob(t($month))),show.rownames = F,show.colnames = F)

ggplot(df,aes(x=month,fill=month)) +
    geom_bar() +
    ylim(0,150) +
    annotation_custom(mytable,xmin = 4.5,xmax=15,ymin=130,ymax = 150) +

No comments :

Post a Comment