data.frame中的等高线图

use*_*388 1 r contour

考虑以下:

temp <- array(sample(1:100,12), dim=c(365,12))
Depth <- as.vector(seq(1,12,by=1))
time <- seq(from=as.Date("2011-01-01"), to=as.Date("2011-12-31"), by=1)

Data <- data.frame(Time = time, Temp = as.matrix(temp))
colnames(Data) <- c("Datetime", paste(Depth,"m",sep = "")) 
Run Code Online (Sandbox Code Playgroud)

不要考虑生成data.frame时使用的3行,因为它们仅用于生成我目前正在使用的类似示例.data.frame即'Data'包括日期时间向量和在不同深度记录的相应温度测量值,其中每个测量值的深度作为列名称给出.

由此我想生成温度曲线的填充等高线图.因此,我想将DateTime向量作为x值,将col标题作为y值,将temp作为z值.我将如何实现这一目标?

我刚刚从matlab转换为R,所以很抱歉这可能是一个非常简单的问题.

Rei*_*son 6

Lattice让你很容易就是你拥有正确结构的数据(长而细不宽而短 - 你现在拥有它)

首先使用一些简单的数据操作将数据转换为所需的格式

## make the colnames numeric-ish
names(Data)[-1] <- sub("m", "", names(Data)[-1])
## stack the data
Data2 <- data.frame(Time = rep(Data$Datetime, times = ncol(Data)-1),
                    stack(Data[, -1]))
names(Data2)[-1] <- c("Temperature", "Depth")
## make Depth numeric
Data2 <- transform(Data2, Depth = as.numeric(as.character(Depth)))
Run Code Online (Sandbox Code Playgroud)

这给了我们:

> head(Data2)
        Time Temperature Depth
1 2011-01-01          84     1
2 2011-01-02          19     1
3 2011-01-03          25     1
4 2011-01-04          21     1
5 2011-01-05           1     1
6 2011-01-06          26     1
Run Code Online (Sandbox Code Playgroud)

lattice使用以下contourplot()函数加载和绘制数据:

require(lattice)
contourplot(Temperature ~ Time * Depth, data = Data2)
Run Code Online (Sandbox Code Playgroud)

对于此示例数据集,它可能有助于使用

contourplot(Temperature ~ Time * Depth, data = Data2, labels = FALSE,
            region = TRUE)
Run Code Online (Sandbox Code Playgroud)

因为轮廓基本上围绕着微小的数据块形成.

有关?contourplot各种选项的更多信息,请参阅该页面.