R ggplot和facet网格:如何控制x轴断点

Slo*_*ner 14 r ggplot2 plyr

我试图使用ggplot绘制每个日历年的时间序列中的变化,并且我对x轴的精细控制存在问题.如果我不使用scale="free_x"那么我最终得到一个x轴,显示几年以及有问题的年份,如下所示:

具有共同x轴的小平面网格图

如果我确实使用scale="free_x"那么就像人们所期望的那样,我最终会得到每个情节的刻度标签,并且在某些情况下会因情节而异,我不想要:

具有自由x轴的小平面网格图

我已尝试使用scale_x_date等来定义x轴,但没有任何成功.我的问题是:

问:如何控制ggplot facet网格上的x轴断点和标签,使得(时间序列)x轴对于每个面都相同,仅显示在面板的底部,并采用月份格式1,2,3等或'Jan','Feb','Mar'?

代码如下:

require(lubridate)
require(ggplot2)
require(plyr)

# generate data
df <- data.frame(date=seq(as.Date("2009/1/1"), by="day", length.out=1115),price=runif(1115, min=100, max=200))
# remove weekend days
df <- df[!(weekdays(as.Date(df$date)) %in% c('Saturday','Sunday')),]
# add some columns for later
df$year <- as.numeric(format(as.Date(df$date), format="%Y"))
df$month <- as.numeric(format(as.Date(df$date), format="%m"))
df$day <- as.numeric(format(as.Date(df$date), format="%d"))

# calculate change in price since the start of the calendar year
df <- ddply(df, .(year), transform, pctchg = ((price/price[1])-1))

p <- ggplot(df, aes(date, pctchg)) +
  geom_line( aes(group = 1, colour = pctchg),size=0.75) + 
  facet_wrap( ~ year, ncol = 2,scale="free_x") +
  scale_y_continuous(formatter = "percent") +
  opts(legend.position = "none")

print(p)
Run Code Online (Sandbox Code Playgroud)

koh*_*ske 10

这是一个例子:

df <- transform(df, doy = as.Date(paste(2000, month, day, sep="/")))

p <- ggplot(df, aes(doy, pctchg)) +
 geom_line( aes(group = 1, colour = pctchg),size=0.75) + 
 facet_wrap( ~ year, ncol = 2) +
 scale_x_date(format = "%b") +
 scale_y_continuous(formatter = "percent") +
 opts(legend.position = "none")
p
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

你想要这个吗?

诀窍是生成同一个虚拟年份的一年中的一天.

更新

这是dev版本的一个例子(即ggplot2 0.9)

p <- ggplot(df, aes(doy, pctchg)) +
  geom_line( aes(group = 1, colour = pctchg), size=0.75) + 
  facet_wrap( ~ year, ncol = 2) +
  scale_x_date(label = date_format("%b"), breaks = seq(min(df$doy), max(df$doy), "month")) +
  scale_y_continuous(label = percent_format()) +
  opts(legend.position = "none")
p
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述