如果满足条件则删除点,同时保留原始色标

问题描述 投票:0回答:1

我正在尝试删除左半部分点(长< 0.5) from the plot below while retaining the original legend color scale.

但是,我下面的代码产生了以下图。色标从 (-0.5, 0, 0.5, 1) 更改为 (0, 0.25, 0.5, 0.75, 1)。如何修改下面的代码以保留原始色阶?我想将 x 轴限制保持在 0 到 1 之间。

library(fields);library(ggplot2);library(colorRamps);library(dplyr)

loc<-as.matrix(expand.grid(seq(0,1,.03),seq(0,1,.03)))
n=nrow(loc)

matCov<-function(distMat,phi){
  (1+(sqrt(5)*(distMat/phi))+((5*distMat^2)/(3*(phi^2))))*exp(-(sqrt(5)*(distMat/phi)))
}

distMat<-as.matrix(rdist(loc))
CovMat <- matCov(distMat,phi=1)
set.seed(123)
Y <- as.numeric(t(chol(CovMat))%*%rnorm(n))
dat = as.data.frame(cbind(loc[,1:2],Y))
names(dat) = c("long","lat","Y")

ggplot(dat, aes(long, lat)) + 
  geom_raster(aes(fill = Y), interpolate = TRUE) + 
  scale_fill_gradientn(colours=matlab.like(10))+
  theme(legend.title=element_blank())

pick <- function(condition){
  function(d) d %>% filter_(condition)
}

ggplot(dat, aes(long, lat)) + 
  geom_raster(aes(fill = Y), interpolate = TRUE,data = pick(~long > 0.5)) + 
  scale_fill_gradientn(colours=matlab.like(10))+
  theme(legend.title=element_blank())+
  scale_x_continuous(limits=c(0,1))
r ggplot2 raster geom-raster
1个回答
0
投票

我真傻。使用 @zephryl 的建议,下面的代码可以解决这个问题。

ggplot(dat, aes(long, lat)) + 
  geom_raster(aes(fill = Y), interpolate = TRUE,data = pick(~long > 0.5)) + 
  scale_fill_gradientn(colours=matlab.like(10),limits=range(Y))+
  theme(legend.title=element_blank())+
  scale_x_continuous(limits=c(0,1))

© www.soinside.com 2019 - 2024. All rights reserved.