'R two variables in stat_function

I created a dataframe inline with data argument of ggplot. I only needed x values and then I plotted the function y = x ^ 2.

ggplot(data = data.frame(x= seq(0, 10, by = 1)), mapping = aes(x = x)) +
  stat_function(fun = function(x) { x**2},
                geom = "line")

So this is a parabola, which is what I expected.

enter image description here

But what about if I want to plot all the solutions where x and y are both unknown but the solution is known? (I think this is called a Diophantine equation?) This time I put both an x and a y value into the data argument of ggplot, figuring I needed both. But my code just gives me a blank ggplot map without any line or anything in it.

ggplot(data = data.frame(x= seq(0, 10, by = 1), y = seq(0, 10, by = 1)), mapping = aes(x = x)) +
  stat_function(fun = function(x) { x + y = 2 }, 
                geom = "line")
                  

But I think I should have a straight line here. When x = 0, y = 2. When x = 1, y = 1. When x = 2, y = 0...

enter image description here

I must be doing something wrong in the stat_function layer - is that right? How do I add another variable besides just an x?

r


Solution 1:[1]

stat_fun is designed to draw functions, not to solve equations.
In this simple example, if x + y = 2 then the function to draw is y = f(x) = 2 - x.

ggplot(data = data.frame(x= seq(0, 10, by = 1), y = seq(0, 10, by = 1)), mapping = aes(x = x)) +
  stat_function(fun = function(x) { 2 - x }, 
                geom = "line")

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1