Discrete colors in ggplot

[This article was first published on distributed ecology, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Have you ever wanted an easy way to generate continuous color pallettes for a discrete factor? I came across a question over on Stackoverflow about how add color to a ggplot figure. I often find myself with lot’s of categories that are discrete when I want a continuous color plot. This can be achieved by writing a quick little function for your colors as:

1
gs.pal <- colorRampPalette(c("#FFFFFF","#000000"),bias=.1,space="rgb")

Now you’ve got a function called gs.pal that accepts the number of colors you want evenly spaced between the two hex code, e.g. gs.pal(5) will generate 5 different evenly spaced color codes. Here it goes between black and white, but you could do between any colors you want. You can put in as many colors as you want in your color vector. Bias controls how much spacing happens between your parameters. Here’s low spacing, with your pallete function set as going from red to blue to yellow.gs.pal <- colorRampPalette(c("#AF1E2D","#0147FA","#FFFF00"),bias=.1,space="rgb")

small bias parameter

You can get more smoothing (depending on how many different categories you have) by adjusting the bias parameter, here I’ll set it to 1, and you’ll see much better smoothing. `gs.pal <- colorRampPalette(c(“#AF1E2D”,”#0147FA”,”#FFFF00”),bias=1,space=”rgb”)

large bias parameter

Now if you have multiple factors that you want to have continuous like labeling for, all you need to do is create this little function with the colors you want spaced between and then use it in base graphics or ggplot2. For instance in ggplot2 you can just use the line scale_colour_manual(values=gs.pal(5)) to generate discrete color values that appear continuous. This code will generate a nice figure with 5 levels moving from red to blue

ggplot example

To leave a comment for the author, please follow the link and comment on their blog: distributed ecology.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)