6

I want to plot an exponential distribution, something like this for example: enter image description here

But I only know how to simulate a data frame that follow a exponential distribution and plot it.

data =  data.frame(x=rexp(n = 100000, rate = .65))
m <- ggplot(data, aes(x=data$x))
m + geom_density()

From which I get: enter image description here

How can I plot the true exponential distribution instead of a sampled version of the distribution?

josliber
  • 43,891
  • 12
  • 98
  • 133
Chubing
  • 187
  • 1
  • 3
  • 10

4 Answers4

10

The exponential distribution can be obtained with the dexp function, so you can plot it by sampling x values and processing them with that function:

x <- seq(0, 20, length.out=1000)
dat <- data.frame(x=x, px=dexp(x, rate=0.65))
library(ggplot2)
ggplot(dat, aes(x=x, y=px)) + geom_line()

enter image description here

josliber
  • 43,891
  • 12
  • 98
  • 133
7

This might be one of those examples where base R is easier than ggplot:

curve(dexp, xlim=c(0,10))

And a ggplot solution that takes advantage of stat_function(...), which was intended for this.

library(ggplot2)
df <- data.frame(x=seq(0,10,by=0.1))
ggplot(df) + stat_function(aes(x),fun=dexp)

jlhoward
  • 58,004
  • 7
  • 97
  • 140
  • Does this solution work even if you need to assign a parameter like `rate` as used on the accepted answer? – Blaszard Nov 23 '20 at 13:04
  • @Blaszard you could do `curve(dexp(x, rate=1/2), xlim=c(1,10))` or `stat_function(aes(x), fun=function(x) dexp(x, rate=1/2))` – RobinGower Nov 30 '20 at 10:32
6

I believe you are might want to do something like

h<-ggplot(data.frame(x=c(0,7)),aes(x=x))
h<-h+stat_function(fun=dexp,geom = "line",size=2,col="blue",args = (mean=1.5))
h<-h+stat_function(fun=dexp,geom = "line",size=2,col="green",args = (mean=1))
h<-h+stat_function(fun=dexp,geom = "line",size=2,col="red",args = (mean=0.5))

enter image description here

Pierre.Vriens
  • 2,117
  • 75
  • 29
  • 42
Antonio
  • 71
  • 1
  • 4
0
setwd("J:/R projects/phoenixhsl/R scripts")
library(ggplot2)
ggplot(data.frame(x=c(0,7)),aes(x=x))+stat_function(fun=dexp,geom =    "line",size=2,col="orange",args = (mean=0.5))
 ggplot(data.frame(x=c(0,7)),aes(x=x))+stat_function(fun=dexp,geom =     "line",size=2,col="purple",args = (mean=1))
  ggplot(data.frame(x=c(0,7)),aes(x=x))+stat_function(fun=dexp,geom =     "line",size=2,col="blue",args = (mean=1.5))