rggplot2curve

r - Plotting function curves using ggplot


Using R base graphics, I have been able to draw a plot with four curves computed from simple functions with this script:

I0 <- log(1)
I1 <- log(1/2)
b <- .1
d <- .01
d1 <- .014

curve(exp(I0 - b * x), 0, 50, col = "blue", lwd = 2)
curve(exp(d * x) - 1, 0, 50, add = TRUE, col = "orange", lwd = 2)
curve(exp(I1 - b * x), 0, 50, add = TRUE, lty = 2, col = "green", lwd = 2)
curve(exp(d1 * x) - 1, 0, 50, add = TRUE, lty = 2, col = "red", lwd = 2)

Plot using base graphics

But when attempting to reproduce the same plot using ggplot2 and the script below, I got something weird:

library(ggplot2)

I0 <- log(1)
I1 <- log(1/2)
b <- .1
d <- .01
d1 <- .014

base <- ggplot() + xlim(0, 50) +
  geom_function(fun = function(x) exp(I0 - b * x), colour = "blue") +
  geom_function(fun = function(x) exp(d * x), colour = "orange") +
  geom_function(fun = function(x) exp(I1 - b * x), color = "green") +
  geom_function(fun = function(x) exp(d1 * x), color = "red")

plot(base)

Plot using ggplot

Also, how could I change the line width (presumably using geom_line())?

I understand that this is sort of a dumb question, but could someone out there give me some hints?


Solution

  • Your functions don't match is why: missing - 1 on the orange and red lines. linewidth will control the line width.

    ggplot() + xlim(0, 50) +
      geom_function(fun = function(x) exp(I0 - b * x), colour = "blue", linewidth = 0.1) +
      geom_function(fun = function(x) exp(d * x) - 1, colour = "orange", linewidth = 1.5) +
      geom_function(fun = function(x) exp(I1 - b * x), color = "green") +
      geom_function(fun = function(x) exp(d1 * x) - 1, color = "red")
    

    enter image description here

    or with + ggthemes::theme_base()

    enter image description here