我有以下类型的数据:在一块长方形的土地(120x50码)上,有6个(也是矩形的)较小的区域,每个区域都有不同种类的植物。这个想法是为了研究各种植物对鸟类的吸引力。每当一只鸟在陆地上的某个地方落地时,我就有了这只鸟落地的确切坐标。我不关心鸟具体坐在哪里,只关心它是六个区域中的哪一个。为了显示鸟类对各种植物的相对偏好,我想制作一个热图,使最常出现的区域成为最暗的区域。因此,我需要将坐标转换为鸟类访问的区域的代码,然后创建一个热图,显示每个陆地区域的不同偏好。(这项研究比这要复杂一些,但这是大体思路。)
我该如何在R中做到这一点?有没有一个R函数,它接受一个坐标向量,并在这样的热图中旋转它?如果没有,你有关于如何做到这一点的更多提示吗?
发布于 2014-08-20 04:47:50
这不是你想要的答案,但可能会给你一些启发。
# Simulate some data
birdieLandingSimulator <- data.frame(t(sapply(1:100, function(x) c(runif(1, -10,10), runif(1, -10,10)))))
# Assign some coordinates, which ended up not really being used much at all, except for the point colors
assignCoord <- function(x)
{
# Assign the four coordinates clockwise: 1, 2, 3, 4
ifelse(all(x>0), 1, ifelse(!sum(x>0), 3, ifelse(x[1]>0, 2, 4)))
}
birdieLandingSimulator <- cbind(birdieLandingSimulator, Q = apply(birdieLandingSimulator, 1, assignCoord))
# Plot
require(ggplot2)
ggplot(birdieLandingSimulator, aes(x = X1, y = X2)) +
stat_density2d(geom="tile", aes(fill = 1/..density..), contour = FALSE) +
geom_point(aes(color = factor(Q))) + theme_classic() +
theme(axis.title = element_blank(),
axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank()) +
scale_color_discrete(guide = FALSE, h=c(180, 270)) +
scale_fill_continuous(name = "Birdie Landing Location")

发布于 2014-08-20 03:58:01
使用ggplot2。看一下geom_bin2d的示例。这是相当简单的二维箱。请注意,您同时为x和y传入了binwidth:
> df = data.frame(x=c(1,2,4,6,3,2,4,2,1,7,4,4),y=c(2,1,4,2,4,4,1,4,2,3,1,1))
> ggplot(df,aes(x=x, y=y,alpha=0.5)) + geom_bin2d(binwidth=c(2,2))发布于 2014-08-20 05:22:18
如果你不想使用ggplot,你可以使用cut函数将你的数据分到不同的库中。
# Test data.
x <- sample(1:120, 100, replace=T)
y <- sample(1:50, 100, replace=T)
# Separate the data into bins.
x <- cut(x, c(0, 40, 80, 120))
y <- cut(y, c(0, 25, 50))
# Now plot it, suppressing reordering.
heatmap(table(y, x), Colv=NA, Rowv=NA)或者,要实际绘制区域的真实地理位置,您可以使用rect自己绘制方框。您必须计算每个区域中的点数。
# Test data.
x <- sample(1:120, 100, replace=T)
y <- sample(1:50, 100, replace=T)
regions <- data.frame(xleft=c(0, 40, 40, 80, 0, 80),
ybottom=c(0, 0, 15, 15, 30, 40),
xright=c(40, 120, 80, 120, 80, 120),
ytop=c(30, 15, 30, 40, 50, 50))
# Color gradient.
col <- colorRampPalette(c("white", "red"))(30)
# Make the plot.
plot(NULL, xlim=c(0, 120), ylim=c(0, 50), xlab="x", ylab="y")
apply(regions, 1, function (r) {
count <- sum(x >= r["xleft"] & x < r["xright"] & y >= r["ybottom"] & y < r["ytop"])
rect(r["xleft"], r["ybottom"], r["xright"], r["ytop"], col=col[count])
text( (r["xright"]+r["xleft"])/2, (r["ytop"]+r["ybottom"])/2, count)
})

https://stackoverflow.com/questions/25391856
复制相似问题