Skip to content

ggplot2: Plotting two or more overlapping density plots on the same graph

March 16, 2009

One R Tip A Day uses a custom R function to plot two or more overlapping density plots on the same graph.

http://learnr.files.wordpress.com/2009/03/3densities.gif?w=400&h=400

The same can be very easily accomplished in ggplot2.


> library(ggplot2)

Create dummy dataframe:

> df <- data.frame(x = rnorm(1000, 0, 1), y = rnorm(1000,
     0, 2), z = rnorm(1000, 2, 1.5))

“Melt” data:

> df.m <- melt(df)

Default plot:

> ggplot(df.m) + geom_freqpoly(aes(x = value,
     y = ..density.., colour = variable))
http://learnr.files.wordpress.com/2009/03/density3.png?w=416&h=415

Default plot + few formatting adjustments:

> ggplot(df.m) + geom_freqpoly(aes(x = value,
     y = ..density.., colour = variable)) +
     labs(x = NULL) + opts(legend.position = "none") +
     opts(title = "Frequency Polygons (based on binned counts)")
http://learnr.files.wordpress.com/2009/03/density11.png?w=416&h=415

Update: Hadley kindly points out that the above plots are frequency polygons. I have updated the post with a “real” density plot.

> ggplot(df.m) + geom_density(aes(x = value,
     colour = variable)) + labs(x = NULL) +
     opts(legend.position = "none") + opts(title = "Densities from a kernel density estimator")
http://learnr.files.wordpress.com/2009/03/density2.png?w=416&h=415
About these ads
15 Comments leave one →
  1. March 16, 2009 7:14 pm

    Those are frequency polygons (based on binned counts) rather than densities from a kernel density estimator (as from geom_density).

  2. March 16, 2009 8:05 pm

    Nice one; is there any chance of making the lines slightly less ‘jaggedy'; perhaps it’s a question of dpi in ggsave?

    • learnr permalink
      March 17, 2009 12:09 am

      James, at the moment I am using dpi=72, will have a look whether increasing it will make a difference.

      • March 18, 2009 4:54 am

        I wouldn’t think chaning the dpi would help much – it looks like the plots aren’t being correctly anti-aliased (unlike the base graphics plot). How are you saving them?

      • learnr permalink
        March 18, 2009 12:23 pm

        I am using ggsave:
        ggsave(“density2.png”, dpi=72)

        R 2.8.0 on WinXP.

      • March 18, 2009 5:21 pm

        Hmmm, and how did you save the base graphics plot?

      • learnr permalink
        March 18, 2009 6:52 pm

        Actually, I didn’t save it myself.
        I got it from http://onertipaday.blogspot.com/2007/09/plotting-two-or-more-overlapping.html

      • March 18, 2009 10:11 pm

        Ah, ok. I don’t follow R windows development that closely, but it’s possible you may get somewhat better graphics by upgrading to the latest version of R may improve things (the default appearance is much better on mac and linux). Otherwise you might need to save as pdf and then use another graphics program to convert to png.

  3. March 24, 2009 1:25 pm

    I agree width Hadley using the basic code below, under Mac OS X and Linux, the png output is ‘correctly’ anti-aliased and it looks much better:

    library(“ggplot2″)
    png(“densities_plots.png”)
    ggplot(df.m) + geom_density(aes(x=value, y=..density.. ,colour=variable)) + labs(x=NULL) + opts(legend.position=”none”) + opts(title = “Densities from a kernel density estimator”)
    dev.off()

  4. gireesh permalink
    September 21, 2010 7:41 am

    is it possible to get rid of the extra line on x-axis

  5. April 15, 2012 9:45 pm

    How can you make the density lines thicker?

    • learnr permalink*
      April 16, 2012 12:06 pm

      By adjusting the line size attribute:
      ggplot(df.m) + geom_density(aes(x=value, colour=variable), size = 2)
      ggplot(df.m) + geom_density(aes(x=value, colour=variable), size = 3)

      • April 16, 2012 12:30 pm

        Thanks, that’s what I want — that was a combination I hadn’t tried.

  6. October 17, 2012 6:05 pm

    In my version (R 2.15.2) I ve to include ‘library(reshape)’ before using melt

    • learnr permalink*
      October 17, 2012 10:15 pm

      That’s true – ggplot2 does not load reshape by default any more.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 177 other followers

%d bloggers like this: