简体   繁体   中英

facet_wrap, facet_grid - using date type in facets

Consider the following simple example:

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)

The second ggplot fails with error:

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

When I cast column b (date) to character, it works:

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

I can pass any other data type to facet_wrap except date:

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

Is there a way how I can pass date column to facet_wrap or facet_grid without casting the column to character/factor first?

R version 3.0.2 (2013-09-25) ggplot2_0.9.3.1

Generally we split panels using factor . With facets, you have One constraint

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

So Either you cast your b to a factor, or if you want to keep it , you can create a new factor column using it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM