繁体   English   中英

如何将多个密度曲线叠加到R中的一个图中

[英]How to Superimpose Multiple Density Curves Into One Plot in R

我有一个看起来像这样的数据。

我打算在一个图中创建多个密度曲线,其中每个曲线对应于唯一ID。

我尝试使用“sm”包,使用此代码,但没有成功。

library(sm)
dat <- read.table("mydat.txt");
plotfn <- ("~/Desktop/flowgram_superimposed.pdf");
pdf(plotfn);

sm.density.compare(dat$V1,dat$V2, xlab = "Flow Signal")
colfill <- c(2:10);
legend(locator(1), levels(dat$V2), fill=colfill)

dev.off();

请告知正确的方法是什么,或者是否有其他方法可以做到这一点?

我想在最后得到这种情节。 图http://img524.imageshack.us/img524/2736/testl.png

尝试使用ggplot2:

dnow <- read.table("http://dpaste.com/88561/plain/")
library(ggplot2)
qplot(V1, colour=factor(V2), data=dnow, geom="density")

您也可以使用晶格包解决这个问题。

require(lattice)
dnow <- read.table('http://dpaste.com/88561/plain/')
densityplot(~V1, groups=V2, data=dnow)

以意大利面条代码方式使用基本图形:

plot.multi.dens <- function(s)
{
junk.x = NULL
junk.y = NULL
for(i in 1:length(s))
{
junk.x = c(junk.x, density(s[[i]])$x)
junk.y = c(junk.y, density(s[[i]])$y)
}
xr <- range(junk.x)
yr <- range(junk.y)
plot(density(s[[1]]), xlim = xr, ylim = yr, main = "")
for(i in 1:length(s))
{
lines(density(s[[i]]), xlim = xr, ylim = yr, col = i)
}
}
dnow <- read.table("http://dpaste.com/88561/plain/")
library(sqldf)
x <- unlist(sqldf("select V1 from dnow where V2==0"))
y <- unlist(sqldf("select V1 from dnow where V2==1"))
z <- unlist(sqldf("select V1 from dnow where V2==2"))
plot.multi.dens(list(x,y,z))
library(Hmisc)
le <- largest.empty(x,y,.1,.1)
legend(le,legend=c("x","y","z"), col=(1:3), lwd=2, lty = 1)

我发现自己在查看微阵列数据时需要做很多事情,所以我把它作为我保留在github上的实用程序代码库的一部分: ARE.utils ,特别是plot.densities函数。

它使用基本图形,因此您可以从该功能中获取灵感来创建自己的图形,或者只是将其全部销售(但它依赖于该库中的其他一些功能):

  1. create.densities ,它将数据的列表/矩阵/等转换为密度列表;
  2. match.dim函数(将维度“名称”转换为数字轴)。

(你可以选择安装整个软件包,但我不承诺我的功能不会以某种向后不兼容的方式改变)。

编写自己的这样的功能并不难,但只要确保你有功能在轴和东西上选择正确的范围。 无论如何,你会使用这样的代码:

library(ARE.utils)
# Create a matrix dataset with separate observations in columns
dat <- matrix(c(rnorm(100), rnorm(100, mean=3), 
                rnorm(100, mean=3, sd=2)),
              ncol=3)
# Plot them
plot.densities(dat, along='cols')

这将在同一轴上创建三种不同的密度图,并具有自己的颜色。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM