How to plot an exponential distribution
Asked Answered
O

4

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?

Othella answered 21/9, 2015 at 23:5 Comment(1)
curve(0.65*exp(-0.65*x), from=0, to=10)Staley
U
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

Undershoot answered 21/9, 2015 at 23:13 Comment(0)
A
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)

Adulate answered 22/9, 2015 at 6:23 Comment(2)
Does this solution work even if you need to assign a parameter like rate as used on the accepted answer?Litha
@Litha 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))Kristof
B
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

Bracketing answered 29/4, 2016 at 16:0 Comment(0)
G
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))
Germinant answered 26/10, 2016 at 11:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.