独自の関数を作成できる R の ggplot2 の新しい機能を使用しようとしていstat_
ます。2次元配列に配置されたポイント間の補間サーフェスを計算してプロットするための単純なものを作成しています。
x
、y
、およびval
美学を必要とする stat_topo() を作成し、単純な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_
関数の呼び出し内でデフォルトのスケールを設定するにはどうすればよいですか。