MichaelSampson123
MichaelSampson123

Reputation: 87

Creating a Function for a parabola in R, but not translating upwards

I am trying to make a parabola in R to layer on top of my ggplot with the function

y = -(10x-8)^2 + 113

using the code

eqn = function(x) {-(10*x - 8)^2 + 113}

But when I add it to the ggplot using

+ stat_function(fun = eqn) + xlim(115, 0)

It's max is 0, when it should be 113, and if I just remove the 113 nothing changes, so I just do not understand why it does not recognize the "+113" at the end there.

Upvotes: 0

Views: 565

Answers (3)

Peter
Peter

Reputation: 12699

library(ggplot2)


eqn = function(x) {-(10*x - 8)^2 + 113}



``` r
#run as stat_function  
ggplot()+
  stat_function(fun = eqn) + xlim(-1, 2)

# perhaps you meant ylim

ggplot()+
  stat_function(fun = eqn) + ylim(0, 115)

Created on 2021-04-21 by the reprex package (v2.0.0)

Upvotes: 1

Waldi
Waldi

Reputation: 41220

You can get the values of a ggplot using layer_data:

eqn = function(x) {-(10*x - 8)^2 + 113 }

library(ggplot2)

layer_data(ggplot() + stat_function(fun = eqn) + xlim(115, 0))

...
99    -2.30     -112.00     1    -1  black  0.5        1    NA
100   -1.15      100.75     1    -1  black  0.5        1    NA
101    0.00       49.00     1    -1  black  0.5        1    NA

the last value is 49 which is exactly 113 - 8^2 :

eqn(0)
[1] 49

Perhaps you forgot to source again eqn function after adding 113.

Upvotes: 1

Marcos Pérez
Marcos Pérez

Reputation: 1250

Try:

curve(-(10*x-8)^2 + 113, from=-50, to=50,  xlab="x", ylab="y")

Using ggplot2 package:

library(ggplot2)
eq = function(x){-(10*x-8)^2 + 113}
ggplot(data.frame(x=c(-50, 50)), aes(x=x)) + 
  stat_function(fun=eq)

Upvotes: 1

Related Questions