Rainbow Gradient with geom_density2d

748 views
Skip to first unread message

Brandon Hurr

unread,
Jul 7, 2012, 5:48:25 AM7/7/12
to ggplot2, Joran Elias
I saw this point on R-bloggers and wondered if you could fully replicate the plot in ggplot2 with the rainbow color gradient. I couldn't get it to work though. 
Inline image 1
http://www.r-bloggers.com/fix-overplotting-with-colored-contour-lines/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+RBloggers+%28R+bloggers%29


require(ggplot2)
require(scales)
df <- data.frame(x = rnorm(15000),y=rnorm(15000))
ggplot(df,aes(x=x,y=y)) + geom_point() + geom_density2d()

I tried supplying a series of colors, but that failed because you can only supply one fixed color... :/

B
image.png

Joran

unread,
Jul 7, 2012, 10:36:49 AM7/7/12
to ggp...@googlegroups.com
How about stat_contour with colour = ..level.. ?

Brandon Hurr

unread,
Jul 7, 2012, 2:12:37 PM7/7/12
to Dennis Murphy, ggplot2
Very pretty, thanks Joran and Dennis. 

On Sat, Jul 7, 2012 at 7:09 PM, Dennis Murphy <djm...@gmail.com> wrote:
Hi Brandon:

Joran is on the right track, and in fact you can find a suitable template example on the ggplot2-0.9 help pages. I needed some practice, so came up with this:

require(MASS)

require(ggplot2)
require(scales)
df <- data.frame(x = rnorm(15000),y=rnorm(15000))

# 2D density estimate using MASS::kde2d with
# conversion to data frame:
dens <- with(df, kde2d(x, y), n = 50, lims = c(-4, 4, -4, 4))
ddf <- data.frame(expand.grid(xd = dens$x, yd = dens$y),
                  z = as.vector(dens$z))

p <- ggplot(df, aes(x = x, y = y)) +
      geom_point(size = 0.5, alpha = 0.5) +
      stat_contour(data = ddf,
                   aes(x = xd, y = yd, z = z, color = ..level..),
                   size = 1)
p + scale_color_gradient(low = 'maroon', high = 'yellow',
                         guide = 'colorbar')

or alternatively,

ggplot() +
  stat_contour(data = ddf, geom = 'polygon',
               aes(x = xd, y = yd, z = z, fill = ..level..)) +
  geom_point(data = df, aes(x = x, y = y),
               size = 0.5, alpha = 0.5) +
  scale_fill_gradient(low = 'maroon', high = 'yellow',
                       guide = 'colorbar')

HTH,
Dennis



B

--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility
 
To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+u...@googlegroups.com
More options: http://groups.google.com/group/ggplot2


image.png
Reply all
Reply to author
Forward
0 new messages