具有一个对数轴的热图

heat map with one log axis

我有一个数据框,其中单个因变量 (y) 与自变量 x1 具有〜对数线性关系,与自变量 x2 具有〜S 形关系。

df<-data.frame(x1 = rep(c(0:10),11),
           x2 = rep(c(0:10), each=11),
           logx1 = log(rep(c(0:10),11)+1),
           y = 0)

for(i in 1:nrow(df)) df[i,4] = exp(df[i,2]) * (1/(1+exp(-df[i,1])))

我想使用热图显示 y 相对于 x1 和 x2 变化的变化:

ggplot(df, aes(x=x1, y=x2, fill=y))+
 theme_bw()+
 scale_fill_distiller(palette = "Spectral")+
 geom_tile(size=0.01)

但是很难看出 y 相对于 x1 的变化,所以我想在对数刻度上绘制 x1:

ggplot(df, aes(x=logx1, y=x2, fill=y))+
 theme_bw()+
 scale_fill_distiller(palette = "Spectral")+
 geom_tile(size=0.01)+

但它会导致数据之间有很大的空间,而不是连续的颜色表面: gaps in heat map

我试过:

将 x1 转换为因子并绘制:

df$x1<-factor(df$x1, levels = sort(unique(df$x1)))

使用插值绘制为栅格:

geom_raster(interpolate = TRUE

变换轴本身:

scale_x_continuous(breaks = c(0,1,10)+1, limits = c(0,10)+1, trans = 'log')

使用 coord_equal() 和 coord_fixed() 更改地块大小,

增加数据的分辨率(即 x1 每变化 0.001 估计 y)

但我无法让空格消失!

我不一定要在热图上出售,但我需要显示 y 相对于 x1 和 x2 的变化,我需要在 ggplot

中完成

如果 y ~ exp(x) 如您的示例所示,那么将 y(而不是 x)放在对数刻度上可能是显示它们之间关系的更好方式。例如

ggplot(df, aes(x=x1, y=x2, fill=log(y))) +
  theme_bw() +
  scale_fill_distiller(palette = "Spectral") +
  geom_tile(size=0.01)

或者,您可以按指数比例显示 x(请注意,在您的示例中,它实际上是 x2 与 y 和 x1 具有对数线性关系)。如果要在指数尺度上显示 x2 的连续表面热图,则需要 x2 在指数尺度上等距分布的点。获得等距点的一种方法是 pretty() 函数。例如

# generate new data with x2 equally space on exp scale
newdat <- expand.grid(x1 = pretty(df$x1, 10), exp_x2 = pretty(exp(df$x2), 10))

# backtransform exp_x2
newdat$x2 <- log(newdat$exp_x2) 

# generate y values (using raw x2 values, not exp_x2)
newdat$y <- exp(newdat$x2) * (1/(1+exp(-newdat$x1)))

# plot    
ggplot(newdat, aes(x=x1, y=exp_x2, fill=y)) +
  theme_bw() +
  scale_fill_distiller(palette = "Spectral") +
  geom_tile(size=0.01)