Best way to make a custom palette with ggplot2

 


 

 

A better way to pick colours with ggplot2

First, get the excellent package by Marco D Visser:

library(devtools)
install_github("MarcoDVisser/choosecolor")

call it

library(choosecolor)

This lets us interactively pick colors ourselves.
Just for fun and to get the hang of it, experiment with color.choose()

now make a palette. In the syntax below means that you get to pick
4 colors for your palette. Run the command below and click 4 colours.
it'll bring up a colorpicker, click on the colours you want.

Mypalette

plot of chunk unnamed-chunk-3

Now that you have picked the colours you want, you can say how many
colours you want your palette to have. If its greater than the
number you specified above, R will interpolate from what you specified.

Mypalette(10)
Mypalette(5)

OK, nuff messing around. Now let's define two palettes. Pick reddish one

Mypalette.red

And a multi-colored one

Mypalette.mult

OK! Now,let's load up ggplot2

library(ggplot2)

Define some data

df

plot like so (note that for the points, we are coloring the FACTOR
of the value yval2, otherwise a it would want a range

p

which looks like this or so:

p

plot of chunk unnamed-chunk-10

The way to plot manual colors to ggplot2 is using the parameters:

scale_fill_manual()

for fill

p + scale_fill_manual(values=c("#000000", "#3333FF","#000000", "#3333FF",
                               "#000000", "#3333FF","#000000", "#3333FF",
                               "#000000", "#3333FF","#000000", "#3333FF",
                               "#000000", "#3333FF","#000000", "#3333FF",
                               "#000000", "#3333FF","#000000", "#3333FF"))

plot of chunk unnamed-chunk-11

See that black/blue pattern in the bars but not in the dots? We did that.
We passed 20 colors for 20 observations just for show.
PRO TIP: don't pass colors like this… its kinda lame.

and

  scale_colour_manual()

for points and lines

p + scale_colour_manual(values=c("#000000", "#3333FF","#000000", "#3333FF",
                                 "#000000", "#3333FF","#000000", "#3333FF",
                                 "#000000", "#3333FF","#000000", "#3333FF",
                                 "#000000", "#3333FF","#000000", "#3333FF",
                                 "#000000", "#3333FF","#000000", "#3333FF"))

plot of chunk unnamed-chunk-12

Now you see the 2-color pattern in the points but not the bars.

So cool… but not EXACTLY userfriendly. Heres where the palette comes in!

Now use the palette you made in ggplot, and color both bars and dots:

p + scale_fill_manual(values=Mypalette.mult(20)) +
  scale_colour_manual(values=Mypalette.red(20))

Rplot

LIKE A BAWS!!!!

  1 comment for “Best way to make a custom palette with ggplot2

  1. 2015/05/11 at 01:11

    I could not resist commenting. Very well written!

Leave a Reply

%d bloggers like this: