如何使用ggplot绘制概率密度?

发布于 2024-09-26 09:12:40 字数 272 浏览 2 评论 0原文

我正在寻找 ggplot 方法来绘制概率密度函数(或任何函数)。我曾经使用 R 中旧的 plot() 函数来执行此操作。例如,要使用 alpha=1beta=1 (均匀)绘制 beta 分布:

x <- seq(0,1,length=100)
db <- dbeta(x, 1, 1)
plot(x, db, type='l')

如何在 ggplot 中做到这一点?

I am looking for the ggplot way to plot a probability density function (or any function). I used to use the old plot() function in R to do this. For example, to plot a beta distribution with alpha=1 and beta=1 (uniform):

x <- seq(0,1,length=100)
db <- dbeta(x, 1, 1)
plot(x, db, type='l')

How can I do it in ggplot?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七秒鱼° 2024-10-03 09:12:40

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

ggplot2 has a stat_function() function to superimpose a function on a plot in much the same way as curve() does. I struggled a little bit to get this to work without generating the data until I realised how to use the variables produced by the statistic --- here ..y... The following is similar to what you would get with 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
独自←快乐 2024-10-03 09:12:40
library(ggplot2)
x <- seq(0,1,length=100)
db <- dbeta(x, 1, 1)

您可以使用 ggplot2 中的 qplot 函数来制作快速绘图

qplot(x, db, geom="line")

,也可以将 geom_line 图层添加到 ggplot

ggplot() + geom_line(aes(x,db))
library(ggplot2)
x <- seq(0,1,length=100)
db <- dbeta(x, 1, 1)

You can use the qplot function within ggplot2 to make a quick plot

qplot(x, db, geom="line")

or you can add a geom_line layer to a ggplot

ggplot() + geom_line(aes(x,db))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文