![](/img/trans.png)
[英]facets as in facet_grid, and axis.line as for facet_wrap?
[英]facet_wrap, facet_grid - using date type in facets
考慮以下簡單示例:
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_wrap
或facet_grid
而不先將該列強制轉換為character / factor?
R版本3.0.2(2013-09-25)ggplot2_0.9.3.1
通常,我們使用factor
拆分面板。 有了構面,您就有一個約束
至少一層必須包含用於構面的所有變量”
因此,您可以將b強制轉換為一個因子,或者如果要保留它,則可以使用它創建一個新的因子列。
ggplot(data.frame(df,h = as.factor(df$b)), aes(x=d, y=c)) +
geom_line(aes(group=a)) +
facet_wrap(~h)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.