将基本 R 图转换为 ggplot。渐变填充矩形

Translate base R plot to ggplot. Gradient fill rectangles

谁能帮我把下面的基本 R 代码翻译成 ggplot2:

编辑 - 我的 x 值是观察值。例如:

x            <-runif(100,min=0,max=60)
lim_x        <-range(x)
lim_y        <-c(0.5,3.5)
probabilities<-cbind(seq(from=0,to=1,length.out=100),
                     c(seq(from=0,to=1,length.out=50),seq(from=1,to=0,length.out=50)),
                     seq(from=1,to=0,length.out=100))

plot(c(lim_x[1],lim_x[2]), c(lim_y[1], lim_y[2]), type = "n",ylab="",xlab="") 


for(i in 1:ncol(probabilities)){
  p <- probabilities[,i]
  gradient.rect(lim_x[1],i-0.5,lim_x[2],i+0.5,nslices=nrow(probabilities),
                reds=1,greens=1-p,blues=1-p)
}

产生这个情节:

这就是我将基本 R 代码转换为 ggplot2 的方式:

library(ggplot2)

lim_x        <-c(0,60)
lim_y        <-c(0.5,3.5)
probabilities<-cbind(seq(from=0,to=1,length.out=100),
                     c(seq(from=0,to=1,length.out=50),seq(from=1,to=0,length.out=50)),
                     seq(from=1,to=0,length.out=100))


df <- reshape2::melt(probabilities)

ggplot(df, aes(Var1, Var2, fill = value)) +
  geom_tile() +
  scale_fill_gradientn(colours = c("white", "red")) +
  annotate("rect", xmin = min(df$Var1) - 0.5, xmax = max(df$Var1) + 0.5,
           ymin = unique(df$Var2) - 0.5, ymax = unique(df$Var2) + 0.5,
           colour = "black", fill = NA)

reprex package (v2.0.1)

于 2021-09-14 创建

或者,如果您想要完全相同的颜色,您可以使用:

ggplot(df, aes(Var1, Var2)) +
  geom_tile(aes(fill = I(rgb(1, 1 - value, 1 - value)))) +
  annotate("rect", xmin = min(df$Var1) - 0.5, xmax = max(df$Var1) + 0.5,
           ymin = unique(df$Var2) - 0.5, ymax = unique(df$Var2) + 0.5,
           colour = "black", fill = NA)

您必须转换数据

probabilities_long <- matrix(t(probabilities), ncol = 1)

df <- data.frame(x1 = sort(rep(seq(0,60,length.out = 100),3)), 
                 x2 = sort(rep(seq(0.6, 60.6, length.out = 100),3)),
                 y1 = rep(c(0.5, 1.5, 2.5),100),
                 y2 = rep(c(1.5, 2.5, 3.5),100), 
                 prob = matrix(t(probabilities), ncol = 1))

然后你可以使用geom_rect绘制每个方块:

ggplot(df)+
    geom_rect(aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2, fill = prob))+
    scale_fill_gradient(low = "#ffffff",
                          high = "#ff0000")