【发布时间】:2012-01-21 07:27:44
【问题描述】:
我正在尝试使用 ggplot 绘制每个日历年的时间序列变化,但我在 x 轴的精细控制方面遇到了问题。如果我不使用scale="free_x",那么我最终会得到一个 x 轴,显示几年以及相关年份,如下所示:
如果我确实使用了scale="free_x",那么正如人们所期望的那样,我最终会为每个图提供刻度标签,并且在某些情况下会因图而异,这是我不想要的:
我已经多次尝试使用 scale_x_date 等来定义 x 轴,但没有任何成功。因此,我的问题是:
问。如何控制 ggplot 构面网格上的 x 轴中断和标签,以便(时间序列)x 轴对于每个构面都是相同的,仅显示在面板底部,并且格式为月份格式 1, 2、3 等或“一月”、“二月”、“三月”?
代码如下:
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)
【问题讨论】: