我是初学者,尝试用R制作图表。请帮我。我有多列数据(时间序列)。每列都包含因子(请参阅下面的一列示例数据)。我想制作时间序列的恒定高度(比如1个单位)条形图,并希望用不同颜色的“A”和“B”表示x轴上的DATE。有提示吗? 提前感谢你!
DATE GROUP
2011.06.18 00:00:00 R
2011.06.18 06:00:00 L
2011.06.18 12:00:00 R
2011.06.18 18:00:00 R
2011.06.19 00:00:00 L
2011.06.19 06:00:00 L
2011.06.19 12:00:00 R
2011.06.19 18:00:00 L
2011.06.20 00:00:00 L
2011.06.20 06:00:00 L
2011.06.20 12:00:00 R
2011.06.20 18:00:00 L
2011.06.21 00:00:00 R
2011.06.21 06:00:00 L
答案 0 :(得分:1)
假设您的数据位于dat
,但附加了一列:
dat <- structure(list(DATE = structure(list(sec = c(0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0), min = c(0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L), hour = c(0L, 6L, 12L, 18L, 0L, 6L,
12L, 18L, 0L, 6L, 12L, 18L, 0L, 6L), mday = c(18L, 18L, 18L,
18L, 19L, 19L, 19L, 19L, 20L, 20L, 20L, 20L, 21L, 21L), mon = c(5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), year = c(111L,
111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L,
111L, 111L), wday = c(6L, 6L, 6L, 6L, 0L, 0L, 0L, 0L, 1L, 1L,
1L, 1L, 2L, 2L), yday = c(168L, 168L, 168L, 168L, 169L, 169L,
169L, 169L, 170L, 170L, 170L, 170L, 171L, 171L), isdst = c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), .Names = c("sec",
"min", "hour", "mday", "mon", "year", "wday", "yday", "isdst"
), class = c("POSIXlt", "POSIXt")), GROUP = structure(c(2L, 1L,
2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L), .Label = c("L",
"R"), class = "factor"), GROUP2 = structure(c(1L, 2L, 2L, 1L,
2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L), .Label = c("L", "R"), class = "factor")), .Names = c("DATE",
"GROUP", "GROUP2"), row.names = c(NA, -14L), class = "data.frame")
然后我觉得这样做你想要的。首先将元素==计算到其中一个类
counts <- apply(dat[, 2:3], 1, function(x) sum(x == "R"))
然后计算另一个计数并绑定到矩阵:
countmat <- t(cbind(L = (NCOL(dat) - 1) - counts, R = counts))
然后我们使用barplot()
op <- par(mar = c(9,4,4,2) + 0.1, las = 2)
mids <- barplot(countmat, ylim = c(0,2.5),
legend.text = c("L","R"),
args.legend = list(x = "top", bty = "n"))
axis(side = 1, at = mids, labels = as.character(dat$DATE))
par(op)
产生:
有关参数的说明,请参阅各个函数的帮助页面。
修改:如果您只想为单个列执行此操作,那么这不是最有趣的图表,但是......
count2 <- with(dat, GROUP == "R")
countmat2 <- t(cbind(R = count2, L = !count2))
op <- par(mar = c(9,4,4,2) + 0.1, las = 2)
mids <- barplot(countmat2, ylim = c(0, 1.5),
legend.text = c("R","L"),
args.legend = list(x = "top", bty = "n"))
axis(side = 1, at = mids, labels = as.character(dat$DATE))
par(op)
给出了这个数字: