我有两个时间序列如下:
y1 <- mvrnorm(50, c(3,1), matrix(c(0.5,0.3,0.3,0.3),2,2))# 2-D bivariate normal
y2 <- mvrnorm(50, c(1,0), matrix(c(2,.1,.1,1),2,2))# another 2-D bivariate normal
y <- rbind(y1,y2) # append the second to the end of the first
我用ggplot绘制这些:
yd <- as.data.frame(y)
g<- ggplot(data=yd) +
geom_line(aes(x=1:nrow(yd), y=yd$V1, colour= "TS1"))+
geom_line(aes(x=1:nrow(yd), y=yd$V2, colour= "TS2"))+
scale_colour_manual(name= "Levels",
values = c("TS1"= "black",
"TS2" ="blue"))+
labs(title="Two time series")+
xlab("Time") +
ylab("Levels") +
theme(legend.justification = c(1, 0), legend.position = c(1, 0))
然后我运行一个分类器,为每个时间点创建一个类标签的数字向量。下面我绘制后验并提供标签向量。
dput(labels)
c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L)
我希望能够根据从上述标签向量派生的类标签对图1进行颜色编码。要清楚,我希望能够在任何给定时间看到我所处的状态(类),而不仅仅是看到状态转换边界。我认为最直观的做法是在状态转换为第2阶段时更改背景颜色(例如从灰色变为橙色)。
在ggplot中实现这一目标的最佳方法是什么?我显然对其他解决方案建议持开放态度。
答案 0 :(得分:1)
您可以使用geom_ribbon
添加背景颜色等内容。
# creating background data
df_bg <- data.frame(x = c(0, rep(which(as.logical(diff(labels))), each=2), length(labels)),
ymin = 1.1*min(yd$V1, yd$V2),
ymax = 1.1*max(yd$V1, yd$V2),
fill = factor(rep(unique(labels), each=2)))
# plot
g <- ggplot(data=yd, aes(x = seq_along(V1))) +
geom_ribbon(data = df_bg,
aes(x = x, ymin=ymin, ymax=ymax, fill=fill), alpha=.2) +
geom_line(aes(y=V1, color="TS1")) +
geom_line(aes(y=V2, color="TS2")) +
scale_colour_manual(name= "Levels",
values = c("TS1"= "black",
"TS2" ="blue"))+
labs(title="Two time series") +
xlab("Time") +
ylab("Levels") +
theme(legend.justification = c(1, 0), legend.position = c(1, 0))