首页 文章

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

提问于
浏览
14

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

Facet grid plot with common x-axis

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

Facet grid plot with free x-axis

我已尝试使用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 回答

  • 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
    

    enter image description here

    你想要这个吗?

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

    UPDATED

    这是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
    

    enter image description here

相关问题