R 中的热色密度

Heat Color Densities in R

我正在尝试构建一种类似于此处的颜色密度图:

https://stats.stackexchange.com/questions/26676/generating-visually-appealing-density-heat-maps-in-r

但是其中包含不同类型的数据。我的真实数据有很多行,但例如我有代码被放入数据框中,即 X、Y、分数,我想使用这些静态 X、Y 桶绘制颜色密度图。那可能吗?

X=seq(0,10,by=1)
Y=seq(50,60,by=1)
total=expand.grid(X,Y)
nrow(total)
total$score=runif(nrow(total), min=0, max=100)
range(total$score)
head(total)

my_palette <- colorRampPalette(c("blue", "yellow", "red"))(n = 100)
col_breaks = c(seq(0,100,length=100))
col=data.frame(as.character(my_palette),col_breaks)
col$num=row.names(col)
head(col)
col$col_breaks=round(col$col_breaks,0)
names(col)[1]="hex"

total$round=round(total$score)
total$color=as.character(col$hex[match(total$round,col$col_breaks)])

plot(total$Var1,total$Var2,col=total$color,xlim=c(0,10),ylim=c(50,60))

我不是想将 hexbin 或任何东西限制在盒子里,我想出了使用带颜色的条件 rect() 但想知道这种类型的数据是否有办法让它更像一个自由流动的形状热量类似于:

还是需要连续的数据才能做这样的事情?

如果我理解正确你的问题,我想你可以在 ggplot 中做到这一点。

基本上,您可以使用 geom_raster 通过插值选项填充图块,这样它看起来就不会像 "blocky"。然后,您可以将渐变设置为您想要的。因此,例如,根据您给我的示例数据,我将低、中、高颜色分别设置为蓝色、白色和红色。它只是以下代码:

library(ggplot2)

ggplot(total, aes(x=Var1, y=Var2)) + 
  geom_raster(aes(fill=score), interpolate=TRUE) +
  scale_fill_gradient2(limits=c(0,100), low="blue", mid="white", high="red", midpoint = 50)

输出: