我正在寻找使用ggplot绘制概率密度函数(或任何函数)的方法。我曾经使用旧的plot()
函数在R中完成这个任务。例如,要绘制一个具有alpha=1
和beta=1
(均匀分布)的贝塔分布:
x <- seq(0,1,length=100)
db <- dbeta(x, 1, 1)
plot(x, db, type='l')
我该如何在ggplot中实现这个功能?
library(ggplot2)
x <- seq(0,1,length=100)
db <- dbeta(x, 1, 1)
qplot(x, db, geom="line")
ggplot() + geom_line(aes(x,db))
ggplot2有一个stat_function()
函数,可以像curve()
一样在图表上叠加函数。我花了一点时间才想明白如何使用统计量生成的变量(这里是..y..
),才成功地让它工作而不必生成数据。以下类似于使用curve(dbeta(x, shape1 = 2, shape2 = 2), col = "red")
所得到的结果:
require(ggplot2)
x <- seq(0, 1, len = 100)
p <- qplot(x, geom = "blank")
stat <- stat_function(aes(x = x, y = ..y..), fun = dbeta, colour="red", n = 100,
args = list(shape1 = 2, shape2 = 2))
p + stat
错误:美学必须是长度为1或与数据相同(1):x 运行 `rlang::last_error()` 查看错误发生的位置。
- kjetil b halvorsenstat_function()
的东西。等我回到正式的电脑前,我会看一下并更新这个。 - Gavin Simpson
require(ggplot2)
或者library(ggplot2)
? - Gavin Simpson