How to plot a function curve in R

sjdh picture sjdh · Sep 29, 2014 · Viewed 168.6k times · Source

What are the alternatives for drawing a simple curve for a function like

eq = function(x){x*x}

in R?

It sounds such an obvious question, but I could only find these related questions on stackoverflow, but they are all more specific

I hope I didn't write a duplicate question.

Answer

sjdh picture sjdh · Sep 29, 2014

I did some searching on the web, and this are some ways that I found:

The easiest way is using curve without predefined function

curve(x^2, from=1, to=50, , xlab="x", ylab="y")

enter image description here

You can also use curve when you have a predfined function

eq = function(x){x*x}
curve(eq, from=1, to=50, xlab="x", ylab="y")

enter image description here

If you want to use ggplot,

library("ggplot2")
eq = function(x){x*x}
ggplot(data.frame(x=c(1, 50)), aes(x=x)) + 
  stat_function(fun=eq)

enter image description here