2012年2月3日星期五

label the time series plot - ggplot2

Usually, the X-axis would be date/time variables, then how could we specify the right X positions for labels of whatever lines, text or rectangles? 时间序列作图中,X轴通常为时间序列变量。那么此时如果要给这样的图做注释,我们如何确定横轴坐标呢?

Here an example.



d <- data.frame(mon = seq(as.Date('2010-09-01'),

as.Date('2011-05-01'), by = '1 month'),

                y1 = c(9, 10, 9, 11, 10, 11, 10, 9, 9),

                y2 = c(17, 14, 16, 15, 14, 15, 16, 17, 17))

as.numeric(d$mon)

lab1 <- 'First multi-line\nchart annotation'

lab2 <- 'Second multi-line\nchart annotation'



ggplot(d, aes(x = mon)) +

    theme_bw() +

    geom_rect(xmin = 14000, xmax = 16000, ymin = 10, ymax = 30, fill =

'ivory') +

    geom_line(aes(y = y1), colour = 'red', linetype = 'dashed', size = 1) +

    geom_line(aes(y = y2), colour = 'gold', size = 1) +

    geom_text(aes(x = 14900, y = 17.5, label = lab1)) +

    geom_text(aes(x = 14950, y = 12.5, label = lab2)) +

    ylim(0, 20) +

    scale_x_date(major = '1 month', format = '%b') +

    opts(panel.grid.major = theme_blank(),

         panel.grid.minor = theme_blank()) +

    geom_hline(aes(yintercept = seq(0, 20, by = 2.5)), colour = 'grey80')
Created by Pretty R at inside-R.org

没有评论:

发表评论