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

Issue

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.

Solution

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.

Answered By – Waldi

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.