2021-03-16

How to plot functions in R

Problem

We would like to plot functions in R.

Solution

In our example we will plot the following quadratic equation: 2x2 + 20x + 3 = 0

  • Option 1: base package
  • f <- function(x) {
      x ^ 2 + 20 * x + 3
    }
    curve(expr = f, from = -100, to = 100)
    
  • Option 2: ggplot2
  • library(ggplot2)
    ggplot(data.frame(x = c(-100, 100)), aes(x)) +
      stat_function(
        fun = function(x) {
          x ^ 2 + 20 * x + 3
        }
      ) +
      geom_hline(yintercept = 0) +
      geom_vline(xintercept = 0)
    
     

Notes

If we want to add more functions:

  • Option 1: Base package
  • f1 <- function(x) {
      x ^ 2 + 20 * x + 3
    }
    f2 <- function(x) {
      x ^ 2 + 50 * x + 100
    }
    curve(expr = f1, from = -100, to = 100)
    curve(expr = f2, from = -100, to = 100, col  = 2, add = TRUE)
    
  • Option 2: ggplot2
  • ggplot(data.frame(x = c(-100, 100)), aes(x)) +
      stat_function(
        fun = function(x) {
          x ^ 2 + 20 * x + 3
        }
      ) +
      stat_function(
        fun = function(x) {
          x ^ 2 + 50 * x + 100
        },
        colour = "red"
      ) +
      geom_hline(yintercept = 0) +
      geom_vline(xintercept = 0)
     

References

No hay comentarios:

Publicar un comentario

Nube de datos