Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stat_density2d Contour Plot Legend and Points

Tags:

r

ggplot2

I have the following contour plot (I am not able to reproduce the exact same data, so I placed the figure below).

Contour Plot

The code used:

contPlot <- (ggplot(data=gg, aes(x=wf, y=wb, z=z)) + geom_point(aes(colour=z)) 
 + stat_density2d(aes(fill = ..level..),n = 100,contour = TRUE,geom = "polygon"))
contPlot + labs(x=expression(w[f]),y=expression(w[b]))

Now I would like to: -Remove the level legend level, associated with the estimated density. -Remove the points below the estimated density, but keeping the 'z' legend. -Rename the 'z' legend.

How can do the above? I am beginner with ggplot2, so please bear with me. Thanks!

like image 426
user191919 Avatar asked Jun 14 '26 02:06

user191919


1 Answers

This works:

  • Faked some data
  • Then used the shape="" to prevent the points from being shown.
  • Turned off the fill guide, supressing the guide titled "level"
  • I should have been able to change the title of the color legend with guide_legend with the title parameter but that messed up the guide (maybe a gplot2 2.0.0 bug?)
  • So renamed the z variable to the title I wanted (My Title) and enclosed it in backticks so as to give me freedom to choose any title.

Yielding this:

# fake data
set.seed(1234)
n <- 200
gg <- data.frame(wf=rnorm(n,0.5),wb=rnorm(n,0.5),z=runif(n,0,6))

# plot it
gg$`My Title` <- gg$z
ggplot(data=gg, aes(x=wf, y=wb, color=`My Title`)) + 
  geom_point(aes(colour=z),shape="") +
  stat_density2d(aes(fill = ..level..),n = 100,contour = TRUE,geom = "polygon") +
  labs(x=expression(w[f]),y=expression(w[b])) +
  guides(fill=F)

which looks like this:

enter image description here

like image 159
Mike Wise Avatar answered Jun 18 '26 02:06

Mike Wise