Plotting Math Functions In R

Hi. I have played around with the ggplot2 package in R to create math functions plot. Here is some of my findings and experimental work. Make sure to load ggplot2 in R using library(ggplot2).


Table Of Contents

References

A Parabola Example

A Sine Function Plot

The Absolute Function

A Square Root Plot

The Reciprocal Function

A Exponential Function Plot

A Logarithmic Function Plot

An Example Of Combining Two Functions In A Plot


References

http://www.sthda.com/english/wiki/ggplot2-add-straight-lines-to-a-plot-horizontal-vertical-and-regression-lines

R Graphics Cookbook by Winston Chang (2012)


A Parabola Example

Recall that the parabola comes from x^2. In R, the quadratic function is made first. The ggplot() function is then used along with stat_function(fun = quadratic_fun).

The above plot looks okay but it could use some labels. Here is an updated version of the above in the code and output below.

The axes labels have been changed through colour and size. To obtain the y = x^2 on the top, you need the annotate() function. With annotate() you can specify the positioning, text size, fontface and label names.


A Sine Function Plot

This example will be on the sine function or y = \sin(x). The code is very similar to the parabola example above. Note that radians are used over degrees where \pi is equal to 180 degrees or the numeric value of 3.14 (two decimals).

An optional add-on would be adding the y = 0 line.


The Absolute Function

Here is an example of plotting the absolute function. Note that I used ifelse() for the function which is a condensed form of using if, else statements.


A Square Root Plot


The Reciprocal Function

Here is my attempt on the reciprocal function \dfrac{1}{x}. I am not sure if it turned out right. Here is what I have.

You can add on asymptote lines at y = 0 and at x = 0.


A Exponential Function Plot

Axes lines can be added as well.


A Logarithmic Function Plot

The inverse (reverse) of the exponential function is the logarithmic function.

Axes lines can be added as well here.


An Example Of Combining Two Functions In A Plot

In this example, the parabola y = x^2 and the y = x line are put on the same plot.

Leave a Reply