la_leche
la_leche

Reputation: 473

R: ggplot distance formula

I'm trying to plot isoclines under a scatterplot using ggplot but I can't figure out how to use stat_functioncorrectly.

The isoclines are based on the distance formula:

sqrt((x1-x2)^2 + (y1-y2)^2)

and would look like these concentric circles, except the center would be the origin of the plot:

enter image description here

What I've tried so far is calling the distance function within ggplot like so (Note: I use x1=1 and y1=1 because in my real problem I also have fixed values)

 distance <- function(x, y) {sqrt((x - 1)^2 + (y - 1)^2)}
 ggplot(my_data, aes(x, y))+
    geom_point()+
    stat_function(fun=distance)

but R returns the error:

Computation failed in 'stat_function()': argument "y" is missing, with no default

How do I correctly feed x and y values to stat_function so that it plots a generic plot of the distance formula, with the center at the origin?

Upvotes: 3

Views: 774

Answers (1)

Axeman
Axeman

Reputation: 35297

For anything a bit complicated, I avoid the use of the stat functions. They are mostly aimed at quick calculations. They are usually limited to calculating y based on x. I would just pre-calculate the data and the plot with stat_contour instead:

distance <- function(x, y) {sqrt((x - 1)^2 + (y - 1)^2)}
d <- expand.grid(x = seq(0, 2, 0.02), y = seq(0, 2, 0.02))
d$dist <- mapply(distance, x = d$x, y = d$y)

ggplot(d, aes(x, y)) +
  geom_raster(aes(fill = dist), interpolate = T) +
  stat_contour(aes(z = dist), col = 'white') +
  coord_fixed() +
  viridis::scale_fill_viridis(direction = -1)

enter image description here

Upvotes: 2

Related Questions