为ggplot定制x轴标签

时间:2013-11-19 18:55:03

标签: r ggplot2

我正在尝试使用包ggplot中的ggplot2方法绘制以下zoo对象:

library(zoo)
library(scales)
library(ggplot2)
library(grid)

vec =  c(41.27 ,50.35 ,59.18 ,60.93 ,61.35 ,32.13 ,41.18 ,43.69 ,58.48 ,65.02 ,44.61 ,64.89 ,57.4 ,68.67 ,53.6 ,49.2 ,51.85 ,
36.36 ,34.74 ,61.83 ,49.8 ,53.23 ,50.92 ,53.35 ,54.43 ,58.56 ,42.36 ,54.64 ,47.54 ,48.96 ,40.44 ,58 ,43.05 ,58.49 ,51.68 ,
42.22 ,37.79 ,58.7 ,46.69 ,44.68 ,50.48 ,54.92 ,50.23 ,52.49 ,43.93 ,40.7 ,56.64 ,44.46 ,45.81 ,50.4 ,49 ,49.37 ,53.95)
vec.idx =  c("2001-04-30", "2001-05-31", "2001-06-30", "2001-07-31", "2001-08-31", "2001-09-30", "2001-10-31", "2001-11-30", "2001-12-31", "2002-01-31", "2002-02-28",
"2002-03-31", "2002-04-30", "2002-05-31", "2002-06-30", "2002-07-31", "2002-08-31", "2002-09-30", "2002-10-31", "2002-11-30", "2002-12-31", "2003-01-31",
"2003-02-28", "2003-03-31", "2007-11-30", "2007-12-31", "2008-01-31", "2008-02-29", "2008-03-31", "2008-04-30", "2008-05-31", "2008-06-30", "2008-07-31",
"2008-08-31", "2008-09-30", "2008-10-31", "2008-11-30", "2008-12-31", "2009-01-31", "2009-02-28", "2009-03-31", "2010-05-31", "2010-06-30", "2010-07-31",
"2010-08-31", "2011-08-31", "2011-09-30", "2011-10-31", "2011-11-30", "2011-12-31", "2012-01-31", "2012-05-31", "2012-06-30")
vec.zoo = zoo(vec, order.by = as.Date(vec.idx, format = "%Y-%m-%d"))

##### Plot

Time = as.Date(index(vec.zoo))
Value = coredata(vec.zoo)
Group <- c(0, cumsum(diff(index(vec.zoo)) > 31))
Names = paste("Period", Group+1, sep = " ")
start = start(vec.zoo)
end = end(vec.zoo)
x_breaks <- seq(start, end, by="1 year")
x_labels <- as.character(x_breaks, format="%b-%Y")

par(mar=c(0,0,0,0))
g <-ggplot(data.frame(Time, Value, Group, Names)) + geom_line(aes(x=as.Date(Time, format = "%y-%m-%d"), y=Value), color = "cadetblue4", size = 0.75) +
    theme(axis.text.x = element_text(angle = 45, hjust = 1, size=7),axis.text.y = element_text(size=8), axis.title.y = element_text(size = 10), plot.margin = unit(c(1,0.5,0.6,0.5), "inches") ) +
    facet_grid(~ Names, scales = "free_x", labeller = ) + 
    xlab("") + 
    ylab("Hit Rate") + 
    scale_y_continuous(limits = c(0, 100), expand = c(0, 0)) +
    scale_x_date(expand = c(0, 0)) +
    geom_hline(yintercept = mean(vec.zoo), color = "red", size = 0.75)

这是我得到的情节:

enter image description here

我想将x-axis标签仅放置在矢量索引定义的点上。目前,该图显示了一些随机标签,我的载体中没有相应的观察结果。

有人可以告诉我该怎么做?谢谢你的帮助。

0 个答案:

没有答案