1

I want to fill a raster with a function of the x and y axes. My best guess was something like this:

library(ggplot2)

df <- data.frame(x = c(-20,20), y = c(-20,20))
f <- function (x, y) x * y

ggplot(df, aes(x,y)) +
    stat_function(fun = f, geom="raster")

Clearly there's a workaround in creating a matrix, filling it with the values, converting that into a raster object and that into points, but is there an easier way?

tonytonov
  • 25,060
  • 16
  • 82
  • 98
Gregory
  • 4,147
  • 7
  • 33
  • 44

1 Answers1

1

The main idea for such tasks is (as you stated yourself) to precompute values and feed them to ggplot. There is no "direct" way to do what you're asking (at least to my knowledge), but you could take this snippet and wrap it into your own geom. Also check out this question.

coords <- expand.grid(x=seq(-20, 20, by=0.5), y=seq(-20, 20, by=0.5))
coords$value <- apply(coords, 1, FUN=function(x) prod(x))
ggplot(coords, aes(x, y, fill=value)) + 
  geom_raster()

enter image description here

The resolution is controlled by by, obviously.

Community
  • 1
  • 1
tonytonov
  • 25,060
  • 16
  • 82
  • 98