使用 ggplot 和 R 绘制预定义的密度函数
我有三个不同长度的数据集,我想在同一个图上绘制所有三个数据集的密度函数。这对于基本图形来说是直接的:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ggplot2 幸福的秘诀是将所有内容都放在“长”(或者我猜矩阵导向的人们会称之为“稀疏”)格式中:
如果你不想要颜色:
The secret to happiness in ggplot2 is to put everything in the "long" (or what I guess matrix oriented people would call "sparse") format:
If you don't want colors: