Try using ggplot2:
dnow <- read.table("http://dpaste.com/88561/plain/")
library(ggplot2)
qplot(V1, colour=factor(V2), data=dnow, geom="density")
Try using ggplot2:
dnow <- read.table("http://dpaste.com/88561/plain/")
library(ggplot2)
qplot(V1, colour=factor(V2), data=dnow, geom="density")
Using base graphics in a spaghetti code fashion:
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)
I found myself needing to do this a lot when looking at microarray data, so I rolled this up as part of a library of utility code that I keep on github: ARE.utils, specifically the plot.densities function.
It uses base graphics so you can take inspiration from that function to create your own, or just take it whole-sale (but it relies on some other functions in that library):
(You can, optionally, install the entire package, but I make no promises that I the functions in there won't change in some backwards incompatible way).
It's not hard to write your own such function, but just make sure you have the function pick the correct range on the axes and stuff. Anyway, you would then use the code like this:
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')
That would create three different density plots on the same axis with their own colors.
You can also solve this using the lattice package.
require(lattice)
dnow <- read.table('http://dpaste.com/88561/plain/')
densityplot(~V1, groups=V2, data=dnow)