2013-10-17 60 views
4

利用日期類型考慮以下簡單的例子:facet_wrap,facet_grid - 在小面

df <- data.frame(
    a = rep(c('a','b','c'),3), 
    b = as.Date(rep(c('2011-01-01','2011-02-01','2011-03-01'),3)), 
    c = rnorm(9), 
    d = rep(1:3,each=3) 
) 

str(df) 

ggplot(df, aes(x=d, y=c)) + geom_line(aes(group=b)) + facet_wrap(~a) 

ggplot(df, aes(x=d, y=c)) + geom_line(aes(group=a)) + facet_wrap(~b) 

第二ggplot失敗,錯誤:

Error in scale_apply(layer_data, x_vars, scale_train, SCALE_X, panel$x_scales) : 

In addition: Warning message: 
In `[<-.factor`(`*tmp*`, rng, value = c(1L, 2L, 3L, 1L, 2L, 3L, : 
    invalid factor level, NA generated 

當我投列b(日期)到字符,它的工作原理:

df$b <- as.character(df$b) 
ggplot(df, aes(x=d, y=c)) + geom_line(aes(group=a)) + facet_wrap(~b) 

我可以傳遞任何其他數據類型到facet_wrap除了日期:

df <- data.frame(
    a = rep(1:3,3), 
    b = rep(1:3,each=3), 
    c = rnorm(9), 
    f = rep(c('a','b','c'),3), 
    g = as.logical(rep(c(TRUE,FALSE,TRUE),3)), 
    h = as.integer(rep(c(1,2,3),3)), 
    i = rep(c(0.5,1.0,1.5),3), 
    j = as.factor(rep(c('a','b','c'),3)), 
    k = as.complex(rep(c(1,2,3),3)), 
    l = as.Date(rep(c('2011-01-01','2011-02-01','2011-03-01'),3)) 
) 

str(df) 

ggplot(df, aes(x=b, y=c)) + geom_line(aes(group=a)) + facet_wrap(~f) # Character 
ggplot(df, aes(x=b, y=c)) + geom_line(aes(group=a)) + facet_wrap(~g) # Boolean 
ggplot(df, aes(x=b, y=c)) + geom_line(aes(group=a)) + facet_wrap(~h) # Integer 
ggplot(df, aes(x=b, y=c)) + geom_line(aes(group=a)) + facet_wrap(~i) # Numeric 
ggplot(df, aes(x=b, y=c)) + geom_line(aes(group=a)) + facet_wrap(~j) # Factor 
ggplot(df, aes(x=b, y=c)) + geom_line(aes(group=a)) + facet_wrap(~k) # Complex 
ggplot(df, aes(x=b, y=c)) + geom_line(aes(group=a)) + facet_wrap(~l) # Date 

有沒有一種方法,我怎麼能傳遞日期欄facet_wrapfacet_grid無柱鑄造字符/因子第一?

- [R 3.0.2版(2013年9月25日) ggplot2_0.9.3.1

回答

2

一般來說,我們使用factor分割面板。隨着方面,你有一個約束

At least one layer must contain all variables used for facetting"

所以,要麼你投你的B到A的因素,或者如果你想保留它,你可以用它創建一個新的因素列。

ggplot(data.frame(df,h = as.factor(df$b)), aes(x=d, y=c)) + 
    geom_line(aes(group=a)) + 
    facet_wrap(~h) 
+1

我明白了。我已經更新了我的問題,這似乎是'date'是你不能在'facet_wrap'使用的唯一類型。這是一個功能還是錯誤? [文件](http://docs.ggplot2.org/0.9.3.1/facet_wrap.html)完全沒有談到方面可能的數據類型,所以我認爲意圖是支持所有類型。 –

+0

@TomasGreif嗯......也許。需要注意的是你與其他日期類型POSIXct和POSIXlt同樣的錯誤..也許您應該諮詢包維護一個可能的錯誤。 – agstudy