Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting predefined density functions using ggplot and R

Tags:

r

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?

like image 650
JD Long Avatar asked Oct 06 '09 02:10

JD Long


People also ask

How do you plot a density function in R?

To plot the probability density function for a t distribution in R, we can use the following functions: dt(x, df) to create the probability density function. curve(function, from = NULL, to = NULL) to plot the probability density function.

What is density in ggplot2?

A density plot is a representation of the distribution of a numeric variable. It is a smoothed version of the histogram and is used in the same kind of situation. Here is a basic example built with the ggplot2 library.

How do you fill a density plot with color in R?

Change fill colors It is also possible to change manually density plot fill colors using the functions : scale_fill_manual() : to use custom colors. scale_fill_brewer() : to use color palettes from RColorBrewer package. scale_fill_grey() : to use grey color palettes.


1 Answers

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")
like image 108
Eduardo Leoni Avatar answered Nov 10 '22 21:11

Eduardo Leoni