ggplot2: Plotting functions

## knitr configuration: http://yihui.name/knitr/options#chunk_options
opts_chunk$set(comment = "", error= TRUE, warning = FALSE, message = FALSE,
               tidy = FALSE, cache = F, echo = T,
               fig.width = 6, fig.height = 6)

## R configuration
options(width = 116, scipen = 5)

References

Load ggplot2

library(ggplot2)

function stat

path geom is the default

stat_function(mapping = NULL, data = NULL, geom = "path",
              position = "identity", fun, n = 101, args = list(),
              ...)

     fun: function to use
       n: number of points to interpolate along
    args: list of additional arguments to pass to ‘fun’

Provide dummy dataset

p <- ggplot(data = data.frame(x = 0), mapping = aes(x = x))

Define first function

fun.1 <- function(x) x^2 + x

Minimum setting needs stat_function() and xlim()

p + stat_function(fun = fun.1) + xlim(-5,5)

plot of chunk unnamed-chunk-5

More detailed settings with legend

To create a legend, give a string to aes(color = ), and specify the color using scale_color_manual(values = ).

p + layer(geom = "path",        # Default. Can be omitted.
          stat = "function",
          fun = fun.1,          # Give function
          mapping = aes(color = "fun.1") # Give a meaningful name to color
          ) +
    scale_x_continuous(limits = c(-5,5)) +
    scale_color_manual(name = "Function", values = c("blue"))

plot of chunk unnamed-chunk-6

Define more functions

fun.2 <- function(x) -1 * x + 10
fun.3 <- function(x) 3 * x + 2

Plot multiple functions

Use scale_color_manual(values = ) to give colors. The order is the order of the layers. The labels on the legend can be overridden by the labels = option.

p +
    layer(stat = "function",
          fun = fun.1,
          mapping = aes(color = "fun.1")
          ) +
    layer(stat = "function",
          fun = fun.2,
          mapping = aes(color = "fun.2")
          ) +
    layer(stat = "function",
          fun = fun.3,
          mapping = aes(color = "fun.3")
          ) +
    scale_x_continuous(limits = c(-5, 5)) +
    scale_color_manual(name = "Functions",
                       values = c("blue", "red", "green"), # Color specification
                       labels = c("X^2 + X", "-X + 10", "3X + 2"))

plot of chunk unnamed-chunk-8

Shown below is the full specification of values without abbreviation.

    scale_color_manual(
        name = "Functions",
        values = c("fun.1" = "blue", "fun.2" = "red", "fun.3" = "green")
        labels = c("X^2 + X", "-X + 10", "3X + 2"))