我想画一个 Rastrigin function 在R.
为了做到这一点,我创建了一个包含三列的Tibble, x , y 和 value . 但是,由于函数签名是 TF_rastrigin(x) 哪里 X 是一个输入向量,我在正确计算值时遇到问题。我想要一个像这样的藏书:
x
y
value
TF_rastrigin(x)
X
x y value -5.12 5.12 57.84943 -5.11 5.11 56.81394 ...
为了把它传给ggplot。我当前的代码如下:
install.packages("TestFunctions") require(TestFunctions) dim <- 100 mw <- tibble(x = seq(0, pi, length.out = dim), y = seq(0, pi, length.out = dim), value = TF_rastrigin(c(x,y))) ggplot(mw, aes(x = x, y = y ,z = value)) + geom_raster(aes(fill = value)) + geom_contour()
有人能告诉我我做错了什么,或者给我一个更好的建议吗?
x y expand.grid apply
expand.grid
apply
dim <- 100 mw <- expand.grid(x = seq(0, pi, length.out = dim), y = seq(0, pi, length.out = dim)) mw$value <- apply(mw, 1, TF_rastrigin) ggplot(mw, aes(x = x, y = y ,z = value)) + geom_raster(aes(fill = value)) + geom_contour()