Heaton Research

How to Chart a Function in R

R works really well as a quick scientific calculator. I often leave R open simply for quick calculations. R can also be used to quickly graph a function. In this article I will show you how to graph a function with R. The function we will examine is the Sigmoid (or Logistic) function. This function is often used as an activation function for a neural network.

We use the following code to define the sigmoid function.

1
2
3
sigmoid <- function(x) {
1 / ( 1 + exp(-x) )
};

Once the sigmoid function has been created it can easily be queried as follows.

1
sigmoid(0)

The above code would produce 0.5.

Plot a Function

The above function could easily be plotted with the following command.

1
plot(sigmoid,-5,5)

The -5 and 5 specify the range to plot over. This produces the following plot.

!{Sigmoid function graphed in R}(/images/blog/)

If you would like to save your plot to a file, use the following. The plot will be saved to your documents directory.

1
2
3
png('test.png')
plot(sigmoid, xlim=c(-5,5), ylim=c(0,1))
dev.off()

The above code was used to produce the plot that you see here.

Sigmoid Function

If you would like to plot two equations on the same graph, the following code can be used.

1
2
3
plot(sin,-pi,2*pi)
par(new=TRUE)
plot(cos,-pi,2*pi)