2017-05-03 33 views
1

我已经在这里完成了回合,并通过谷歌没有解决方案,所以请尽可能帮助。如何做颜色平滑的二维热图......或绝对值的密度图?

我期待创造这样的事情:用painSensitivityHeatMap GGPLOT2

我可以创建使用geom_tile有点类似的东西,但没有数据点...我发现的唯一解决方案之间的平滑需要大量的代码和数据插值。我觉得不是很优雅。 uglySolutionUsingTile

所以我想,我能要挟density2d图谋我的目的,而不是由具有情节使用固定的值,而不是计算数据点的密度 - 多在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

我猜测geom_density需要连续输入(与热图不同)。也许转换为数字并更改标签?请参阅https://wahani.github.io/2015/12/smoothScatter-with-ggplot2/ – timfaber

+0

请参阅'?stat_contour'。如果你想平滑事情,你需要一个插值模型。 – Axeman

+0

我会看看https://en.wikipedia.org/wiki/Kriging。 '克里格'包有一行解决方案来插入要绘制的数据。 – troh

回答

0

这花了我一小会儿,但这里是供将来参考

一个解决方案使用IDW从SP包gstat包和spsample解决方案。

我写了一个函数,它需要一个数据帧,块的数量(tile)以及颜色比例的低位和高位锚点。

该函数创建一个多边形(一个5x5的简单象限),并从中创建该形状的网格。

在我的数据中,位置变量是有序因子 - 因此,我将它们分类为数字(1到5对应于多边形网格)并将它们转换为坐标 - 从而将tmpDF从datafra转换为一个空间数据框。注意:没有重叠/重复的位置 - 即对应于5x5网格的25个观测值。

idw函数使用反距离加权值填充多边形网格(newdata)...换句话说,它将我的数据插值到给定数量的图块('块')的完整多边形网格。

最后,我创建一个基于颜色梯度从该colorRamps包

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) 
} 

我希望这是有用的人的答复一ggplot ...谢谢...之上,他们帮助我继续前进。