使用 ggplot 和 R 绘制预定义的密度函数

发布于 2024-08-06 13:18:34 字数 605 浏览 1 评论 0原文

我有三个不同长度的数据集,我想在同一个图上绘制所有三个数据集的密度函数。这对于基本图形来说是直接的:

n <- c(rnorm(10000), rnorm(10000))
a <- c(rnorm(10001), rnorm(10001, 0, 2))
p <- c(rnorm(10002), rnorm(10002, 2, .5))

plot(density(n))
lines(density(a))
lines(density(p))

这给了我这样的东西:

alt text http://www.cerebralmastication.com/wp-content/uploads/2009/10/密度.png

但我真的想用 GGPLOT2 来做到这一点,因为我想添加其他功能,这些功能只能通过GGPLOT2。看来 GGPLOT 真的想拿我的经验数据来帮我计算密度。这让我大吃一惊,因为我的数据集长度不同。那么如何在 GGPLOT2 中绘制这三种密度呢?

I have three data sets of different lengths and I would like to plot density functions of all three on the same plot. This is straight forward with base graphics:

n <- c(rnorm(10000), rnorm(10000))
a <- c(rnorm(10001), rnorm(10001, 0, 2))
p <- c(rnorm(10002), rnorm(10002, 2, .5))

plot(density(n))
lines(density(a))
lines(density(p))

Which gives me something like this:

alt text http://www.cerebralmastication.com/wp-content/uploads/2009/10/density.png

But I really want to do this with GGPLOT2 because I want to add other features that are only available with GGPLOT2. It seems that GGPLOT really wants to take my empirical data and calculate the density for me. And it gives me a bunch of lip because my data sets are of different lengths. So how do I get these three densities to plot in GGPLOT2?

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

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

发布评论

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

评论(1

流绪微梦 2024-08-13 13:18:34

ggplot2 幸福的秘诀是将所有内容都放在“长”(或者我猜矩阵导向的人们会称之为“稀疏”)格式中:

df <- rbind(data.frame(x="n",value=n),
            data.frame(x="a",value=a),
            data.frame(x="p",value=p))
qplot(value, colour=x, data=df, geom="density")

如果你不想要颜色:

qplot(value, group=x, data=df, geom="density")

The secret to happiness in ggplot2 is to put everything in the "long" (or what I guess matrix oriented people would call "sparse") format:

df <- rbind(data.frame(x="n",value=n),
            data.frame(x="a",value=a),
            data.frame(x="p",value=p))
qplot(value, colour=x, data=df, geom="density")

If you don't want colors:

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