Plot functions in R with coordinate axis and arrows

Viewed 345

I'm a relative beginner in R so please forgive me if it's a noob question.

So, is there a package which provides an easy interface to plot (real-real, mathematical) functions? I need coordinate axis with arrows (and their intersection should be (0;0)) and ticks, grid, etc. I want similar plots as in this document.

Background: now I create function plots with LaTeX's tikzpicture and axis but I'm using R to generate randomized exams since few months (R creates tex-files and include them into document) and would be nice if R can create similar plots (png, jpg), because axis in LaTeX is very slow.

Thanks!

2 Answers

I made you a little function for this

math_plot <- function(f, xlim = c(-2,2), ylim = c(-2,2), 
                      xlab = "x", ylab = "f(x)", ax.ext = .02,
                      frame.plot = F, grid.tick = .1, ...){

  curve(f, from = xlim[1], to = xlim[2], ylim = ylim, 
                      axes = F, xlab = "", ylab = "",
                      frame.plot = frame.plot, ...)

  # x-axis
  axis(1, pos = 0)
  arrows(x0 = xlim[2], x1 = xlim[2] + diff(xlim)*ax.ext, y0 = 0, length = .1)
  mtext(text = xlab, side = 4, line = 0, las = 2, at = 0)

  # y-axis
  axis(2, pos = 0, las = 2)
  arrows(y0 = ylim[2], y1 = ylim[2] + diff(ylim)*ax.ext, x0 = 0, length = .1)
  mtext(text = ylab, side = 3, line = 0, at = 0)

  grid(nx = diff(xlim)/grid.tick, ny = diff(ylim)/grid.tick)
}

# give it a function
math_plot(function(x) 3*x + 2 - 2*x^2, ylim = c(-2,4))

enter image description here

With R graphic tools such as arrows, points, abline, etc. you can draw practically anything.

Example

op <- par(mar=c(1, 1, 1, 1))  ## adjust outer margins
plot(x, y, type="n", axes=F, asp=1, xlab="", ylab="")  ## asp=1 to maintain 1:1 aspect ratio
lines(x, y, lwd=2)
arrows(par()$usr[1], 0, par()$usr[2], length=.05)  ## par()$usr helps to find xlim and ylim
arrows(0, par()$usr[3], 0, par()$usr[4], length=.05)
points((-5:5)*10, rep(0, 11), pch=3, cex=.6)  ## pch=3 for crosses
points(rep(0, 11), (-5:5)*10, pch=3, cex=.6)
mtext("y", 3, -1, adj=.55, font=8)
mtext("x", 4, -1, padj=-1, las=2, font=8)
abline(h=(-5:5)*10, lty=3, col="gray")
abline(v=(-5:5)*10, lty=3, col="gray")
text(10, -4, "10", font=7, cex=.8)
text(-4, 10, "10", font=7, cex=.8)
par(op)  ## reset par

enter image description here


Data

x <- (-10):10; y <- x^2 - 50
Related