我有一个看起来像这样的数据框
head(data1, 30)
date cur.gas
1 2015-01-01 00:00:45 RD
2 2015-01-01 00:02:45 RD
3 2015-01-01 00:04:45 RD
4 2015-01-01 00:06:45 RD
5 2015-01-01 00:08:45 RD
6 2015-01-01 00:10:45 RD
7 2015-01-01 00:12:45 RD
8 2015-01-01 00:14:45 RD
9 2015-01-01 00:16:45 RD
10 2015-01-01 00:18:45 RD
11 2015-01-01 00:20:45 RD
12 2015-01-01 00:22:45 RD
13 2015-01-01 00:24:45 RD
14 2015-01-01 00:26:45 RD
15 2015-01-01 00:28:45 RD
16 2015-01-01 00:30:45 RD
17 2015-01-01 00:40:45 BL
18 2015-01-01 00:42:45 BL
19 2015-01-01 00:44:45 BL
20 2015-01-01 00:46:45 BL
21 2015-01-01 00:48:45 BL
22 2015-01-01 00:50:45 BL
23 2015-01-01 00:52:45 BL
24 2015-01-01 00:54:45 BL
25 2015-01-01 00:56:45 BL
26 2015-01-01 00:58:45 BL
27 2015-01-01 01:00:45 BL
28 2015-01-01 01:46:45 RD
29 2015-01-01 01:50:45 RD
30 2015-01-01 01:52:45 RD
当cur.gas柱指示哪条线(红色(RD)或蓝色(BL))将样品送入分析仪。我想根据这些数据创建水平条形图,它会显示与当前行(红色和蓝色)对应的颜色。
我尝试过使用ggplot:
ggplot(data=data1, aes(x=0.1, y = date, col=cur.gas)) +
geom_bar(stat = "identity", width = 0.1) +
coord_flip() +
scale_fill_manual(values = c("red","blue")) +
theme(text = element_text(size = 10), axis.title = element_blank(), axis.text = element_blank(),
axis.ticks = element_blank())
看起来很可怕,而且颜色错误(图例为BL提供红色,为RD提供蓝色)。
然后我尝试了barplot功能:
attach(data1)
barplot(date,names.arg=cur.gas, horiz = TRUE, col = c("blue", "red"), legend = rownames(data1$cur.gas))
我收到了这个错误:
Error in barplot.default(date, names.arg = cur.gas, horiz = TRUE, col = c("blue", :
'height' must be a vector or a matrix
我现在迷路了。我该怎么办?非常感谢1
答案 0 :(得分:1)
barplot想要的是 INTERVALS 。
data[,"end_date"] <- c(data[-1,1], as.POSIXct("2015-01-01 01:54:45")) # I deciced a last value arbitrarily
data[,"interval"] <- difftime(data$end_date, data$date)
difftime(data$date[1], tail(data$end_date, n=1), units="min") # total 114 min
barplot(matrix(data$interval, ncol=1), horiz=T, col=c(2,4)[data$cur.gas], axes=F)
axis(1, at=seq(0,114,10), las=2, cex.axis=0.8, # If you don't need border, add border=NA
labels=format(seq(data[1,1], tail(data$end_date, n=1), by="10 min"),"%H:%M:%S"))
但它更容易使用geom_rect()
(此代码需要end_date)
ggplot(data) +
geom_rect(aes(xmin=date, xmax=end_date, ymin=0, ymax=1, fill=cur.gas), colour="black") +
theme(axis.text.y=element_blank(), axis.ticks.y=element_blank()) + labs(x="time")
# if you don't need border, delete colour="black".