次の簡単な例を考えてみましょう。
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)
2 番目の 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
R バージョン 3.0.2 (2013-09-25) ggplot2_0.9.3.1