在ggplot geom_raster

时间:2019-05-21 06:57:03

标签: r ggplot2 interpolation logistic-regression geom-raster

使用一个简单的逻辑增长模型,我想绘制一个基于轮廓/梯度的图,以显示增长参数(r)如何改变曲线的斜率和渐近线。

我想在绘制的曲线之间进行插值,而不只是显示一组线。

所以我尝试了以下方法:

#Using these packages
library(ggplot2)
library(tidyr)

# The logistic function applied to a vector of time steps (t)
# K is carrying capacity - asymptote
# N0 is initial population density
# r is growth rate - slope
LogGr <- function(r,K,N0,t){
  d <- vapply(t,function(t) K/(1+(K/N0-1)*exp(-r*t)),numeric(1))
}

# time steps - daily over 4 years
t<-1:(365*4)

# r values - lots of them
r <- as.list(seq(0,0.1,0.001))

# using lapply to run each growth parameter - faster than for loop
ld <- lapply(r,LogGr,K=1,N0=0.00001,t=t)

# create data frame - col of population densities (N) for each r value
df <- data.frame(matrix(unlist(ld), nrow=length(t), byrow=F))
# Add time column (days)
df$Days <- t
# Rename cols for ease of viewing
colnames(df) <- c(as.character(as.vector(r)),"Days")

# Transform to long data format - facilitate ggplot colouring
Data <- gather(df,key=Gr,value=N,-Days)

# GGplot geom_raster plot
# My problem lies here somewhere - I may be misunderstanding the interpolate param.
ggplot(Data,aes(x=Days,y=round(N,3)))+
  geom_raster(aes(fill=as.numeric(Gr)),interpolate=T)+
  labs(y="Population Density",col="Growth Rate")

我希望颜色在曲线之间插值。

编辑: 将给定范围内的r值的数量增加到seq(0,0.1,0.00001)之后,我可以使用上述代码通过插值生成栅格。

所以这个问题变成了“如何控制geom_raster中的插值将传播多远?但这可能是一个重复的问题。更新即将推出。

1 个答案:

答案 0 :(得分:2)

我建议对任务使用stat_summary_hex()geom。我提供了缩放功能,让您可以使用填充比例。根据需要输入类似viridis::scale_fill_viridis(rescaler = scale_fn)的内容。

scale_fn <- function(x, to = c(0, 1), from = NULL) {
    ifelse(x<max(x)/10, 
           scales::rescale(x,
                           to = to,
                           from = c(0, max(x)/10)),
           1)}

ggplot(Data,aes(x=Days,y=round(N,3)))+
  stat_summary_hex(aes(z=as.numeric(Gr)))+
  labs(y="Population Density",col="Growth Rate")+
  viridis::scale_fill_viridis()

enter image description here

要使用geom_raster,您应该为每个网格点都有一个值。插值参数将使每个栅格平铺之间的值平滑,从而使生成的图像看起来平滑。

尝试以下操作以查看区别:

ggplot(faithfuld, aes(waiting, eruptions)) +
 geom_raster(aes(fill = density), interpolate = TRUE)