2013-05-16 113 views
9

我在這裏有一個非常簡單的問題。我有2009-2012年的數據集。我想用facet來繪製數據。我已經創建瞭如下的多面情節。將ggplot上的x軸顯示爲僅在R中的月份

R-代碼

ggplot(al02428400,aes(x=date,y=as.numeric(Discharge)))+geom_line()+ylab("Discharge(cfs)")+facet_wrap(~Year,scales=("free_x"))+theme_bw() 

上述R代碼的輸出如下所示:

enter image description here

在X軸我只想顯示的月份。默認情況下顯示月份和年份。有什麼辦法可以擺脫一年?

的完全可再現碼如下所示:

library(ggplot2) 

url <- "http://nwis.waterdata.usgs.gov/usa/nwis/uv/?cb_00060=on&cb_00065=on&format=rdb&period=&begin_date=2009-01-01&end_date=2012-12-31&site_no=02428400" 
download.file(url,destfile="Data load for stations/data/alabamariver-at-monroeville-2009.txt") 

al02428400 <- read.table("Data load for stations/data/alabamariver-at-monroeville-2009.txt",header=T,skip=1,sep="\t") 
head(al02428400) 

sapply(al02428400,class) 
al02428400 <- al02428400[-1,] 

names(al02428400)<- c("Agency","SiteNo","Datetime", "TZ","Discharge","Status","Gageheight","gstatus") 
al02428400$date <- strptime(al02428400$Datetime, format="%Y-%m-%d %H:%M") 

al02428400$Discharge <- as.numeric(as.character(al02428400$Discharge)) 
al02428400$Year <- as.numeric(format(al02428400$date, "%Y")) 
ggplot(al02428400,aes(x=date,y=as.numeric(Discharge)))+geom_line()+ylab("Discharge(cfs)")+facet_wrap(~Year,scales=("free_x"))+theme_bw() 

感謝。

回答

13

由於您的x值是日期,您可以使用scale_x_date()來更改標籤的格式。需要庫scales才能獲得更好的中斷和標籤格式。

library(scales) 
+scale_x_datetime(labels = date_format("%b")) 
+0

感謝您的回答。然而,當我嘗試使用它時,我得到一個錯誤'錯誤:無效輸入:date_trans只與Date類的對象一起工作。我使用的日期格式是POSIXct。 –

+0

@Jdbaba然後你應該使用scale_x_datetime()。更新了我的回答 –

+1

非常感謝。 'scale_x_datetime'完美無缺。 –