我尝试在R中使用ggplot2的新功能,允许创建我们自己的stat_
函数.我正在创建一个简单的计算和绘制排列在2d数组上的点之间的插值表面.
我想创建一个stat_topo()要求x
,y
以及val
美学,绘制简单的geom_raster
内插的val
映射fill
.
library(ggplot2) library(dplyr) library(akima) cpt_grp <- function(data, scales) { #interpolate data in 2D itrp <- akima::interp(data$x,data$y,data$val,linear=F,extrap=T) out <- expand.grid(x=itrp$x, y=itrp$y,KEEP.OUT.ATTRS = F)%>% mutate(fill=as.vector(itrp$z)) # str(out) return(out) } StatTopo <- ggproto("StatTopo", Stat, compute_group = cpt_grp, required_aes = c("x","y","val") ) stat_topo <- function(mapping = NULL, data = NULL, geom = "raster", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( stat = StatTopo, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, ...) ) } set.seed(1) nchan <- 30 d <- data.frame(val = rnorm(nchan), # some random values to be mapped to fill color x = 1:nchan*cos(1:nchan), # the x and y position of the points to interpolate y = 1:nchan*sin(1:nchan)) plot(d$x,d$y) ggplot(d,aes(x=x,y=y,val=val)) + stat_topo() + geom_point()
当我运行它时,我收到以下错误:
Error: numerical color values must be >= 0, found -1
据我所知,这是因为某种程度上fill
美学的规模被设定为离散的.
如果我输入:
ggplot(d,aes(x=x,y=y,val=val)) + stat_topo() + scale_fill_continuous() + geom_point()
我得到了我想要的东西:具有连续色标的预期光栅,我希望默认情况下stat_
这样做...
所以我想问题是:如何防止ggplot在这里设置离散比例,理想情况下在我的新stat_
函数调用中设置默认比例.