我试图使用ggplot绘制每个日历年的时间序列中的变化,并且我对x轴的精细控制存在问题 . 如果我不使用 scale="free_x"
那么我最终会得到一个显示几年以及相关年份的x轴,如下所示:
如果我确实使用了 scale="free_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)
1 回答
这是一个例子:
你想要这个吗?
诀窍是生成同一个虚拟年份的一年中的某一天 .
UPDATED
这是dev版本的一个例子(即ggplot2 0.9)