簡體   English   中英

R ggplot和facet網格:如何控制x軸斷點

[英]R ggplot and facet grid: how to control x-axis breaks

我試圖使用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)

這是一個例子:

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

在此輸入圖像描述

你想要這個嗎?

訣竅是生成同一個虛擬年份的一年中的一天

更新

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

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM