我已经完成了这里的游戏并通过谷歌没有解决方案,所以请尽可能帮助。
我希望使用ggplot2创建这样的内容:painSensitivityHeatMap
我可以使用geom_tile创建类似的东西,但没有数据点之间的平滑......我发现的唯一解决方案需要大量的代码和数据插值。我认为不是很优雅。uglySolutionUsingTile
所以我在思考,我可以通过使用固定值而不是计算的数据点密度来强制密度二维图来实现我的目的 - 这与stat ='相同。同一性'可以在直方图中使用它们来表示数据值,而不是数据计数。
这是一个最小的工作示例:
df <- expand.grid(letters[1:5], LETTERS[1:5])
df$value <- sample(1:4, 25, replace=TRUE)
# A not so pretty, non-smooth tile plot
ggplot(df, aes(x=Var1, y=Var2, fill=value)) + geom_tile()
# A potentially beautiful density2d plot, except it fails :-(
ggplot(df, aes(x=Var1, y=Var2)) + geom_density2d(aes(color=..value..))
答案 0 :(得分:0)
这花了我一点时间,但这是一个供将来参考的解决方案
使用gstat包中的idw和sp包中的spsample的解决方案。
我写了一个函数,它采用数据帧,块数(tile)以及颜色标度的低和高锚。
该函数创建一个多边形(一个5x5的简单象限),并从中创建一个该形状的网格。
在我的数据中,位置变量是有序因子 - 因此我将它们分解为数字(1到5对应于多边形网格)并将它们转换为坐标 - 从而将tmpDF从datafra转换为a空间数据帧。注意:没有重叠/重复的位置 - 即25个对应于5x5网格的观察结果。
idw函数用反距离加权值填充多边形网格(newdata)...换句话说,它将我的数据插入到给定数量的图块('blocks')的完整多边形网格中。 / p>
最后,我根据colorRamps包中的颜色渐变创建了一个ggplot
painMapLumbar <- function(tmpDF, blocks=2500, lowLimit=min(tmpDF$value), highLimit=max(tmpDF$value)) {
# Create polygon to represent the lower back (lumbar)
poly <- Polygon(matrix(c(0.5, 0.5,0.5, 5.5,5.5, 5.5,5.5, 0.5,0.5, 0.5), ncol=2, byrow=TRUE))
# Create a grid of datapoints from the polygon
polyGrid <- spsample(poly, n=blocks, type="regular")
# Filter out the data for the figure we want
tmpDF <- tmpDF %>% mutate(x=unclass(x)) %>% mutate(y=unclass(y))
tmpDF <- tmpDF %>% filter(y<6) # Lumbar region only
coordinates(tmpDF) <- ~x+y
# Interpolate the data as Inverse Distance Weighted
invDistanceWeigthed <- as.data.frame(idw(formula = value ~ 1, locations = tmpDF, newdata = polyGrid))
p <- ggplot(invDistanceWeigthed, aes(x=x1, y=x2, fill=var1.pred)) + geom_tile() + scale_fill_gradientn(colours=matlab.like2(100), limits=c(lowLimit,highLimit))
return(p)
}
我希望这对某人有用...感谢上面的回复......他们帮助我继续前进。