从 R 中的点绘制热图

lbe*_*gni 3 charts r heatmap

我想从一组点在 R 中绘制一个热图。

我有一个像

X  Y  col
1  2  1
1  1  4
2  4  9
.......
Run Code Online (Sandbox Code Playgroud)

我想从中得到一个热图,X 和 Y 是点的坐标,col 可以是 0 到 40。我试图以点或使用melt() 绘制,但没有运气。

我可以用 geom_point() 绘制一些点,但我希望从一种颜色平滑过渡到另一种颜色,有些可能不是正确的做法。

luk*_*keA 5

set.seed(1)
library(ggplot2)
df <- as.data.frame(expand.grid(1:50, 1:50))
df$col <- sample(0:40, size = nrow(df), replace = TRUE)
ggplot(df, aes(x = Var1, y = Var2, colour = col, fill = col )) + 
  geom_tile()
Run Code Online (Sandbox Code Playgroud)

产生:

在此处输入图片说明

编辑:

和这个

set.seed(1)
library(ggplot2)
df <- as.data.frame(expand.grid(1:50, 1:50))
df$col <- sample(0:40, size = nrow(df), replace = TRUE)
df <- df[sample(1:nrow(df), nrow(df) * .2, replace = FALSE), ]  # make holes
df <- df[rep(1:nrow(df), df$col), -3]
ggplot(df, aes(x = Var1, y = Var2)) + 
  geom_point() + 
  stat_density2d(aes(fill=..density..), geom = "tile", contour = FALSE) +
  scale_fill_gradient2(low = "white", high = "red")
Run Code Online (Sandbox Code Playgroud)

产生

在此处输入图片说明