R - Smoothing color and adding a legend to a scatterplot

好久不见. 提交于 2019-12-03 03:54:48

Here are some solutions using the ggplot2 package.

# Load library
library(ggplot2)

# Recreate the scatterplot from the example with default colours
ggplot(df) +
  geom_point(aes(x=x, y=y, col=dens))

# Recreate the scatterplot with a custom set of colours. I use rainbow(100)
ggplot(df) +
  geom_point(aes(x=x, y=y, col=dens)) +
  scale_color_gradientn(colours=rainbow(100))

# A 2d density plot, using default colours
ggplot(df) +
  stat_density2d(aes(x=x, y=y, z=dens, fill = ..level..), geom="polygon") +
  ylim(-0.2, 1.2) + xlim(-30, 180) # I had to twiddle with the ranges to get a nicer plot

# A better density plot, in my opinion. Tiles across your range of data
ggplot(df) +
  stat_density2d(aes(x=x, y=y, z=dens, fill = ..density..), geom="tile", 
                 contour = FALSE)

# Using custom colours. I use rainbow(100) again.
ggplot(df) +
  stat_density2d(aes(x=x, y=y, z=dens, fill = ..density..), geom="tile", 
                 contour = FALSE) +
  scale_fill_gradientn(colours=rainbow(100))

# You can also plot the points on top, if you want
ggplot(df) +
  stat_density2d(aes(x=x, y=y, z=dens, fill = ..density..), geom="tile", 
                 contour = FALSE) +
  geom_point(aes(x=x, y=y, col=dens)) +
  scale_colour_continuous(guide=FALSE) # This removes the extra legend

I attach the plots as well:

Also, using ggplot2, you can use color and size together, as in:

ggplot(df, aes(x=x, y=y, size=dens, color=dens)) + geom_point() + 
scale_color_gradientn(name="Density", colours=rev(rainbow(100))) +
scale_size_continuous(range=c(1,15), guide="none")

which might make it a little clearer.

Notes:

  1. The expression rev(rainbow(100)) reverses the rainbow color scale, so that red goes with the larger values of dens.

  2. Unfortunately, you cannot combine a continuous legend (color) and a discrete legend (size), so you would normally get two legends. The expression guide="none" hides the size legend.

Here's the plot:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!