4

考虑以下简单示例:

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-09-25) ggplot2_0.9.3.1

4

1 回答 1

3

通常我们使用factor. 使用构面,您有一个约束

至少一层必须包含用于分面的所有变量"

因此,您可以将 b 转换为一个因子,或者如果您想保留它,您可以使用它创建一个新的因子列。

ggplot(data.frame(df,h = as.factor(df$b)), aes(x=d, y=c)) + 
  geom_line(aes(group=a)) + 
  facet_wrap(~h)
于 2013-10-17T10:44:17.717 回答