我想使用“lattice”包的levelplot函数将概率分布函数(PDF)绘制为R中的热图。我将PDF作为函数实现,然后使用两个向量为值范围和外部函数生成级别图的矩阵。 我希望轴显示我的问题是我无法在显示两个实际值范围而不是列数或行数的两个轴上添加适当间隔的标记。
# PDF to plot heatmap
P_RCAconst <- function(x,tt,D)
{
1/sqrt(2*pi*D*tt)*1/x*exp(-(log(x) - 0.5*D*tt)^2/(2*D*tt))
}
# value ranges & computation of matrix to plot
tt_log <- seq(-3,3,0.05)
tt <- exp(tt_log)
tt <- c(0,tt)
x <- seq(0,8,0.05)
z <- outer(x,tt,P_RCAconst, D=1.0)
z[,1] <- 0
z[which(x == 1),1] <- 1.5
z[1,] <- 0.1
# plot heatmap using levelplot
require("lattice")
colnames(z) <- round(tt, 2)
rownames(z) <- x
levelplot(z, cex.axis=1.5, cex.lab=1.5, col.regions=colorRampPalette(c("blue", "yellow","red", "black")), at=seq(0,1.9,length=200), xlab="x", ylab="time t", main="PDF P(x,t)")
如果没有为列和行指定名称,我会收到以下图表,其中刻度线自然间隔(如从其他R函数中使用的那样),但值是行和列。列号:
通过为列和行指定名称,我会收到以下图表,其中刻度线根本不可读,但至少对应于实际值:
我已经花了太多时间在这个看似微不足道的问题上,所以我非常感谢你们的任何帮助!
答案 0 :(得分:3)
也许这个基本的例子可以提供帮助,
d = data.frame(x=rep(seq(0, 10, length=nrow(volcano)), ncol(volcano)),
y=rep(seq(0, 100, length=ncol(volcano)), each=nrow(volcano)),
z=c(volcano))
library(lattice)
# let lattice pick pretty tick positions
levelplot(z~x*y, data=d)
# specific tick positions and labels
levelplot(z~x*y, data=d, scales=list(x=list(at=c(2, 5, 7, 9),
labels=letters[1:4])))
# log scale
levelplot(z~x*y, data=d, scales=list(y=list(log=TRUE)))
这一切都在?xyplot
中描述,但不可否认,这是一长篇文档。
答案 1 :(得分:1)
这是我如何使用levelplot
和data.frame
对象(根据baptiste提供的解决方案)最终实现我的函数P(x,t)的热图图:
# PDF to plot heatmap
P_RCAconst <- function(xx,tt,D)
{
1/sqrt(2*pi*D*tt)*1/xx*exp(-(log(xx) - 0.5*D*tt)^2/(2*D*tt))
}
# value ranges & computation of matrix to plot
tt_end <- 20 # set end time
xx_end <- 8 # set spatial boundary
tt <- seq(0,tt_end,0.01) # variable for time
xx <- seq(0,xx_end,0.01) # spatial variable
zz <- outer(xx,tt,P_RCAconst, D=1.0) # meshgrid for P(x,t)
zz[,1] <- 0 # set initial condition
zz[which(xx == 1),1] <- 4.0 # set another initial condition
zz[1,] <- 0.1 # set boundary condition
# plot heatmap using levelplot
setwd("/Users/...") # set working dirctory
png(filename="heatmapfile.png", width=500, height=500) #or: x11()
par(oma=c(0,1.0,0,0)) # set outer margins
require("lattice") # load package "lattice"
d = data.frame(x=rep(seq(0, xx_end, length=nrow(zz)), ncol(zz)),
y=rep(seq(0, tt_end, length=ncol(zz)), each=nrow(zz)),
z=c(zz))
levelplot(z~x*y, data=d, cex.axis=1.5, cex.lab=1.5, cex.main=1.5, col.regions=colorRampPalette(c("blue", "yellow","red", "black")), at=c(seq(0,0.5,0.01),seq(0.55,1.4,0.05),seq(1.5,4.0,0.1)), xlab="x", ylab="time t", main="PDF P(x,t) for RC A, constant population")
dev.off()
这就是我的函数P(x,t)的最终热图图如下: