Sunday, May 18, 2014

Changing the color ramp in contMap or densityMap

I recently received the following question:

"Would it be possible in contMap to specify our own color ramp instead of stuck with the default red-to-blue?"

This cannot yet be done automatically, but it is not too hard. Here are a couple of examples. Note that they also apply equally to objects created using densityMap.

> ## first create simulated tree & data
> tree<-pbtree(n=26,tip.label=LETTERS[26:1])
> x<-fastBM(tree)
> ## build object of class "contMap"
> obj<-contMap(tree,x,plot=FALSE)
> obj
Object of class "contMap" containing:

(1) A phylogenetic tree with 26 tips and 25 internal nodes.

(2) A mapped continuous trait on the range (-4.458, 2.5).

> ## default colors
> plot(obj)
> ## what is the length of the current color ramp?
> n<-length(obj$cols)
> ## change to grey scale
> obj$cols[1:n]<-grey(0:(n-1)/(n-1))
> plot(obj)
> ## change to blue -> red
> obj$cols[1:n]<-colorRampPalette(c("blue","red"), space="Lab")(n)
> plot(obj)

That's it!

5 comments:

  1. Hi,

    First at all, thanks for the support you are doing to phytools. It's so helpful.

    How can I represent a contMap with invert colors respect to the default?

    Cheers,
    Francisco.

    ReplyDelete
  2. I reply myself :o)

    obj$cols[1:n] <- rev(obj$col[1:n])

    ReplyDelete
    Replies
    1. The only problem with this code is that the names of obj$cols also get reversed. Check on my post on this here. Thanks for the feedback Francisco!

      Al the best, Liam

      Delete
  3. Hello,
    I was wondering if it's possible to use a "pre-built" palette for a contMap, and how, instead of specifying the colors. In particular, I would like to use the inferno and magma palettes of the viridis package.

    Thank you very much,
    Giulia

    ReplyDelete
    Replies
    1. Answered myself:
      n<-length(maps$cols)
      maps$cols[1:n] <- viridis(n)

      Delete

Note: due to the very large amount of spam, all comments are now automatically submitted for moderation.