plot.zoo - 绘制一张不同颜色的图表
plot.zoo - Plot one graph with different colors
我想绘制一个时间序列图 return 在资产上用不同的颜色表示更不稳定的时期。我希望将波动集群标记为红色,将其余更平静的时期标记为蓝色。我附上了我想要实现的目标的图像。
我的代码:
plot.zoo(djr, xlab = "Time", ylab = "Returns", col = "blue")
如果 cond
是一个符合您的条件的逻辑向量,适用于更不稳定的时期(例如 cond <- abs(Returns > 0.05)
),您可以使用类似的东西:
plot.zoo(djr, xlab = "Time", ylab = "Returns", col = "blue")
points(index(djr)[cond], djr[cond], type = "l", col = "red")
对于红色的多个时间段,可能会出现从一个到另一个的线条。在下面的例子中我解决了这个问题:
# Reproducible example:
library(zoo)
djr <- as.zoo(EuStockMarkets[, "DAX"])
djr <- (djr - mean(djr))/sd(djr)
cond <- abs(as.numeric(djr)) > 0.75
rlec <- rle(cond)
plot.zoo(djr, xlab = "Time", ylab = "Returns", col = "white")
ind <- 1
for(i in 1:length(rlec$values)) {
points(index(djr)[ind:(ind + rlec$lengths[i] - 1)],
djr[ind:(ind + rlec$lengths[i] - 1)],
type = "l", col = c("blue", "red")[rlec$values[i] + 1])
ind <- ind + rlec$lengths[i]
}
胡安的回答有效。这是我发现也有效的替代方法
ling_segs <-ifelse(djr <= -0.02 | djr >= 0.02, cbind(djr), NA)
line_segs <- na.omit(ling_segs)
plot.zoo(cbind(djr, line_segs),
plot.type = "single",
xlab = "Date", ylab = "Returns",
col = c("blue", "red"))
我想绘制一个时间序列图 return 在资产上用不同的颜色表示更不稳定的时期。我希望将波动集群标记为红色,将其余更平静的时期标记为蓝色。我附上了我想要实现的目标的图像。
我的代码:
plot.zoo(djr, xlab = "Time", ylab = "Returns", col = "blue")
如果 cond
是一个符合您的条件的逻辑向量,适用于更不稳定的时期(例如 cond <- abs(Returns > 0.05)
),您可以使用类似的东西:
plot.zoo(djr, xlab = "Time", ylab = "Returns", col = "blue")
points(index(djr)[cond], djr[cond], type = "l", col = "red")
对于红色的多个时间段,可能会出现从一个到另一个的线条。在下面的例子中我解决了这个问题:
# Reproducible example:
library(zoo)
djr <- as.zoo(EuStockMarkets[, "DAX"])
djr <- (djr - mean(djr))/sd(djr)
cond <- abs(as.numeric(djr)) > 0.75
rlec <- rle(cond)
plot.zoo(djr, xlab = "Time", ylab = "Returns", col = "white")
ind <- 1
for(i in 1:length(rlec$values)) {
points(index(djr)[ind:(ind + rlec$lengths[i] - 1)],
djr[ind:(ind + rlec$lengths[i] - 1)],
type = "l", col = c("blue", "red")[rlec$values[i] + 1])
ind <- ind + rlec$lengths[i]
}
胡安的回答有效。这是我发现也有效的替代方法
ling_segs <-ifelse(djr <= -0.02 | djr >= 0.02, cbind(djr), NA)
line_segs <- na.omit(ling_segs)
plot.zoo(cbind(djr, line_segs),
plot.type = "single",
xlab = "Date", ylab = "Returns",
col = c("blue", "red"))