R中的热色密度

时间:2016-05-12 22:31:13

标签: r plot colors square

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

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

但是有不同类型的数据。我的实际数据有很多行,但是例如我有一些代码被放入X,Y,Score的数据框中,我想要使用这些静态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()但是想知道这种类型的数据是否有办法让它更像是一种自由流动的热量形状类似于:

a busy cat

或者是否需要连续数据来做类似的事情?

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的问题,我认为您可以在ggplot中执行此操作。

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

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)

输出:

enter image description here