1

我正在尝试使用 ggplot2“geom_raster”函数将两个 data.frame 绘制为两层。顶层包含设置为“透明”的 NA 值,以使底层可见。由于 scale_fill_xxx 函数不能使用两次,我尝试了以下代码(基于这篇文章:ggplot2 - using two different color scales for overlay plots):

library(ggplot2)

df1 <- data.frame(x=rep(c(1,2,3),times=3), y=c(1,1,1,2,2,2,3,3,3), data= c(NA,4,9,NA,2,7,NA,NA,3))
df2 <- data.frame(x=rep(c(1,2,3),times=3), y=c(1,1,1,2,2,2,3,3,3), data= c(1,NA,NA,2,NA,NA,1,2,NA))

ggplot() + 
geom_raster(data=df1, aes(y= y, x= x, fill= data)) + 
scale_fill_gradientn(name="df1", colours=c("red", "blue"), na.value = "transparent") + 
geom_raster(data= df2, aes(y= y, x= x, colour= as.factor(data))) + 
scale_colour_manual(values = c("green", "black"), name= "df2", labels= c("Class 1", "Class 2"), na.value="transparent")

问题是“颜色”/“scale_colour_manual”解决方案没有返回我所期望的(它返回一个深灰色图)。我希望df1“数据”列以红色到蓝色的比例表示(NA应该是透明的),df2“数据”列根据类号表示(“1”=绿色和“2”=黑色)。

谁能帮助我了解我的程序有什么问题?

4

1 回答 1

0

这是一个解决方案:

df3 = merge(df1, df2, by = c("x","y"))
names(df3)[names(df3) == "data.x"] <- "data.1"
names(df3)[names(df3) == "data.y"] <- "data.2"
df3$data = df3$data.1
df3$data[is.na(df3$data)] = df3$data.2[is.na(df3$data)]

myGrad <- colorRampPalette(c('blue','red')) # color gradient
min_value = min(df3$data[df3$data >2]) # minimum value except 1 and 2
max_value = max(df3$data) # maximum value 
param = max_value - min_value + 1 # number of colors in the gradient


ggplot(df3, aes(x, y, fill = data)) + geom_raster() + 
scale_fill_gradientn(colours=c("green","black", myGrad(param)), 
values = rescale(c(1, 2, seq(min_value, max_value, 1))), na.value = "transparent")

3x3 图片

我猜你会使用这个具有更高值和范围的图,我尝试使用 5x5 矩阵:

set.seed(123)
df4 = data.frame(x=rep(c(1,2,3,4,5),5), y=c(rep(1,5), rep(2,5), rep(3,5), rep(4,5), rep(5,5)), 
data = sample(c(1:20), 25, prob = c(0.2,0.2,rep(0.6/18,18)), replace = T))
min_value = min(df4$data[df4$data >2])
max_value = max(df4$data)
param = max_value - min_value + 1 

ggplot(df4, aes(x, y, fill = data)) + geom_raster() + 
scale_fill_gradientn(colours=c("green","black", myGrad(param)), 
values = rescale(c(1, 2, seq(min_value, max_value, 1))), na.value = "transparent")

在此处输入图像描述

于 2016-11-09T11:48:05.513 回答