Search code examples
rplotaxis-labels

Plot functions in R with coordinate axis and arrows


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!


Solution

  • 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