[英]How to avoid gaps due to missing values in matplot in R?
我有一個 function 使用matplot
到 plot 一些數據。 數據結構是這樣的:
test = data.frame(x = 1:10, a = 1:10, b = 11:20)
matplot(test[,-1])
matlines(test[,1], test[,-1])
到目前為止,一切都很好。 但是,如果數據集中存在缺失值,則結果 plot 中存在間隙,我想通過連接間隙的邊緣來避免這些間隙。
test$a[3:4] = NA
test$b[7] = NA
matplot(test[,-1])
matlines(test[,1], test[,-1])
在實際情況下,這是在 function 內,矩陣的維度更大,行數、列數和非重疊缺失值的 position 可能會在不同調用之間發生變化,所以我想找到一個解決方案可以靈活地處理這個問題。 我還需要使用matlines
我在想也許可以用內推數據填補空白,但也許有更好的解決方案。
我今天遇到了這種確切的情況,但我不想插入值 - 我只是想讓線條“跨越間隙”,可以這么說。 我想出了一個解決方案,在我看來,它比插值更優雅,所以我想即使問題很老,我也會發布它。
導致差距的問題是連續值之間存在NA
。 所以我的解決方案是“移動”列值,以便沒有NA
間隙。 例如,由c(1,2,NA,NA,5)
組成的列將變為c(1,2,5,NA,NA)
。 我在apply()
循環中使用一個名為shift_vec_na()
的函數來做到這一點。 x 值也需要調整,因此我們可以使用相同的原理將 x 值組成一個矩陣,但使用 y 矩陣的列來確定要移動哪些值。
下面是函數的代碼:
# x -> vector
# bool -> boolean vector; must be same length as x. The values of x where bool
# is TRUE will be 'shifted' to the front of the vector, and the back of the
# vector will be all NA (i.e. the number of NAs in the resulting vector is
# sum(!bool))
# returns the 'shifted' vector (will be the same length as x)
shift_vec_na <- function(x, bool){
n <- sum(bool)
x[1:n] <- x[bool]
x[(n + 1):length(x)] <- NA
return(x)
}
# x -> vector
# y -> matrix, where nrow(y) == length(x)
# returns a list of two elements ('x' and 'y') that contain the 'adjusted'
# values that can be used with 'matplot()'
adj_data_matplot <- function(x, y){
y2 <- apply(y, 2, function(col_i){
return(shift_vec_na(col_i, !is.na(col_i)))
})
x2 <- apply(y, 2, function(col_i){
return(shift_vec_na(x, !is.na(col_i)))
})
return(list(x = x2, y = y2))
}
然后,使用示例數據:
test <- data.frame(x = 1:10, a = 1:10, b = 11:20)
test$a[3:4] <- NA
test$b[7] <- NA
lst <- adj_data_matplot(test[,1], test[,-1])
matplot(lst$x, lst$y, type = "b")
今天也有同樣的問題。 在我的上下文中,我不允許進行插值。 我在這里提供了一個最小但足夠通用的工作示例來說明我所做的事情。 我希望它能幫助某人:
mymatplot <- function(data, main=NULL, xlab=NULL, ylab=NULL,...){
#graphical set up of the window
plot.new()
plot.window(xlim=c(1,ncol(data)), ylim=range(data, na.rm=TRUE))
mtext(text = xlab,side = 1, line = 3)
mtext(text = ylab,side = 2, line = 3)
mtext(text = main,side = 3, line = 0)
axis(1L)
axis(2L)
#plot the data
for(i in 1:nrow(data)){
nin.na <- !is.na(data[i,])
lines(x=which(nin.na), y=data[i,nin.na], col = i,...)
}
}
核心“技巧”在x=which(nin.na)
中。 它使線的數據點與 x 軸的索引一致。
台詞
plot.new()
plot.window(xlim=c(1,ncol(data)), ylim=range(data, na.rm=TRUE))
mtext(text = xlab,side = 1, line = 3)
mtext(text = ylab,side = 2, line = 3)
mtext(text = main,side = 3, line = 0)
axis(1L)
axis(2L)`
繪制 window 的圖形部分。range range(data, na.rm=TRUE)
將 plot 調整為能夠包含所有data
點的適當大小。 mtext(...)
用於 label 軸並提供主標題。 軸本身由axis(...)
命令繪制。
-loop plots the data.以下循環繪制數據。
mymatplot 的 function head 為典型的mymatplot
參數的可選通道提供了...
參數, cex
lty
、 plot
、 lwt
等 via 。 這些將傳遞給lines
。
最后說一下 colors 的選擇——它們完全符合您的口味。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.