如何绘制指数分布

How to plot an exponential distribution

我想绘制指数分布,例如:

但我只知道如何模拟服从指数分布的数据框并绘制它。

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

从中我得到:

如何绘制真正的指数分布而不是分布的抽样版本?

指数分布可以用 dexp 函数得到,所以你可以通过采样 x 个值并用那个函数处理它们来绘制它:

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()

这可能是 base R 比 ggplot 更容易的例子之一:

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

还有一个利用 stat_function(...) 的 ggplot 解决方案,专为此而设计。

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

我相信你可能想做类似的事情

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))

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))