【问题标题】:R ggplot colour labelling time series based on class基于类的R ggplot颜色标记时间序列
【发布时间】:2015-04-06 09:19:30
【问题描述】:

我有两个时间序列如下:

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 中实现这一目标的最佳方法是什么?我显然愿意接受其他解决方案建议。

【问题讨论】:

  • 在时移时用geom_vline()画一条垂直线?
  • 但是如果我假设 3 个状态,我将不知道是从状态 1 到状态 3 还是从状态 1 到状态 2 的转变。(我明白你的意思,但会将其添加到问题)

标签: r ggplot2 time-series classification timeserieschart


【解决方案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)) 

【讨论】:

  • 完美! :) 我还没有尝试理解代码?geom_ribbon,但我是否认为这也适用于 N 个州?
  • 我认为调用中的fill = factor(rep(unique(labels), each=2)) 位是硬编码的,即如果在所描述的两个之后有另一个状态转移,它就不起作用。如果我正确理解您的代码,更通用的解决方案是:fill = factor(rep(labels[c(which(as.logical(diff(labels))), length(labels) )], each=2))
猜你喜欢
  • 2014-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多