2012年2月3日星期五

align facets in case of factor variables (time series)

如果X轴是时间序列变量,那么如何把这些X轴对齐排列呢?

Here is an example.



ex <- structure(list(Time = structure(c(1278428400, 1278429300,
1278430200, 1278431100, 1278432000, 1278432900, 1278433800, 1278434700,
1278435600, 1278436500, 1278437400, 1278438300, 1278439200, 1278440100,
1278441000, 1278441900, 1278442800, 1278443700, 1278444600, 1278445500,
1278446400, 1278447300, 1278448200, 1278449100, 1278450000, 1278450900,
1278451800, 1278452700, 1278453600, 1278454500, 1278455400, 1278456300,
1278457200), class = c("POSIXt", "POSIXct")), `Temperature 1` = c(23.4994760481,
23.5691608609, 23.4065467209, 23.3366466476, 23.7551289027, 23.8713964903,
23.8017531186, 23.8713964903, 23.8017531186, 23.7319104094, 23.7086908787,
23.7086908787, 23.6390259428, 23.6390259428, 23.7319104094, 23.7086908787,
23.7086908787, 23.7783463702, 23.8713964903, 23.9874496028, 24.0572606946,
24.2428788024, 24.3126625639, 24.4750221758, 24.4054436873, 24.4518300234,
24.4286371978, 24.6375394346, 24.7768442676, 24.6375394346, 24.6839132299,
24.4982136668, 24.8695770905), `Temperature 2` = c(26.1917071192,
26.4004768163, 26.7251744961, 26.6092703221, 26.5627215105, 27.0035834406,
26.7251744961, 26.5627215105, 26.7019928016, 26.6324503199, 26.8412800193,
26.7251744961, 26.8876497084, 26.8180959444, 26.7715392541, 26.7715392541,
26.6788115483, 26.8180959444, 26.8644646035, 26.9803955621, 27.0965310426,
27.1197219834, 27.0501510521, 27.0267719079, 26.7947223403, 26.8644646035,
26.9572082609, 27.2124923147, 27.560865829, 27.514456368, 27.5376606738,
27.6536951709, 27.4446582586), sources = c(1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0), status = structure(c(2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("closed",
"open"), class = "factor")), .Names = c("Time", "Temperature 1",
"Temperature 2", "sources", "status"), row.names = c(NA, -33L
), class = "data.frame")

ex$status <- 100 + (ex$status=="open")
melted <- melt(ex,id.vars="Time")
melted$shortvar <- substring(melted$variable,1,11) # This is to put both temperature readings on the same facet.
melted$value2 <- ifelse(melted$shortvar=="Temperature",melted$value,NA)
melted$value <- ifelse(is.na(melted$value2),melted$value,NA)
ggplot(melted, aes(x=Time)) +
 geom_point(aes(y=value2)) +
 geom_line(aes(y=value,group=variable)) +
 facet_grid(shortvar ~ ., scales="free", space="free") +
 scale_y_continuous(expand=c(.1,0), breaks=seq(0,101,1),
minor_breaks=seq(0,100,.5),
 labels=c(as.character(seq(0,99)),"closed","open"))
Created by Pretty R at inside-R.org

没有评论:

发表评论