当 NA 时有条件地遮蔽 dygraph 时间序列的区域
Conditionally shade regions of dygraph time series when NA
我想在时间序列中的值为 NA
的位置添加背景阴影,而不需要指定日期范围。 dygraphs
中的基本阴影选项是这样工作的:
library(dygraphs)
dygraph(nhtemp, main = "New Haven Temperatures") %>%
dyShading(from = "1920-1-1", to = "1930-1-1") %>%
dyShading(from = "1940-1-1", to = "1950-1-1")
我想为缺失的时间序列的大约 50 个区域添加背景阴影,因此手动完成是不可行的。举个简单的例子,我如何告诉 dygraphs
在不指定日期范围的情况下为这个时间序列中的缺失值添加背景阴影?
nhtemp2 <- nhtemp
nhtemp2[10:20] <- NA
dygraph(nhtemp2, main = "New Haven Temperatures")
可能的解决方案:
library(dygraphs)
nhtemp2 <- nhtemp
nhtemp2[10:20] <- NA
nhtemp2[30:45] <- NA
# Convert years to DyShading date format
dates <- sprintf('%d-1-1',time(nhtemp2))
# find NA intervals
start = dates[which(diff(is.na(nhtemp2))==1)]
stop = dates[which(diff(is.na(nhtemp2))==-1)+1]
g <- dygraph(nhtemp2, main = "New Haven Temperatures")
# Loop over NA intervals to add shading
for (i in 1:length(start)) {
g <- dygraphs::dyShading(
g,
from = start[i],
to = stop[i],
color = 'lightgrey')
}
g
请注意,这仅在时间序列不是以 NA
开头时有效,但可以改进以应对此问题。
我想在时间序列中的值为 NA
的位置添加背景阴影,而不需要指定日期范围。 dygraphs
中的基本阴影选项是这样工作的:
library(dygraphs)
dygraph(nhtemp, main = "New Haven Temperatures") %>%
dyShading(from = "1920-1-1", to = "1930-1-1") %>%
dyShading(from = "1940-1-1", to = "1950-1-1")
我想为缺失的时间序列的大约 50 个区域添加背景阴影,因此手动完成是不可行的。举个简单的例子,我如何告诉 dygraphs
在不指定日期范围的情况下为这个时间序列中的缺失值添加背景阴影?
nhtemp2 <- nhtemp
nhtemp2[10:20] <- NA
dygraph(nhtemp2, main = "New Haven Temperatures")
可能的解决方案:
library(dygraphs)
nhtemp2 <- nhtemp
nhtemp2[10:20] <- NA
nhtemp2[30:45] <- NA
# Convert years to DyShading date format
dates <- sprintf('%d-1-1',time(nhtemp2))
# find NA intervals
start = dates[which(diff(is.na(nhtemp2))==1)]
stop = dates[which(diff(is.na(nhtemp2))==-1)+1]
g <- dygraph(nhtemp2, main = "New Haven Temperatures")
# Loop over NA intervals to add shading
for (i in 1:length(start)) {
g <- dygraphs::dyShading(
g,
from = start[i],
to = stop[i],
color = 'lightgrey')
}
g
请注意,这仅在时间序列不是以 NA
开头时有效,但可以改进以应对此问题。