briatte / ggnet

Network visualization with ggplot2
https://briatte.github.io/ggnet/
194 stars 33 forks source link

ColorBrewer palette problems #14

Closed andrewd789 closed 8 years ago

andrewd789 commented 8 years ago

Hello,

I've been using ggnet2 to make network plots from igraph-generated networks. I've done this by using

gr <- as_data_frame(ig, what = "both")

, then using ggnet2 to plot from the resulting dataframes. In general, this works very well. But I'm having some trouble setting color palettes.

This works:

ggnet2(gr$edges, node.color = gr$vertices$Kingdom, palette = "Set1")

But this doesn't work:

ggnet2(gr$edges, node.color = gr$vertices$Kingdom, palette = brewer.pal(10, "Set1"))

And neither does defining a color palette separately, then referring to it with the ggnet2 function.

I get an error like this:

Error in grDevices::col2rgb(colour, TRUE) : 
  invalid color name 'FUNGI'

So I seem to be limited to the number of colors provided in the default colour brewer palettes. Which isn't ideal. Why does this happen?

Andrew.

briatte commented 8 years ago

When using the palette argument, you can either provide your own color palette as a named vector, such as

palette = c("FUNGI" = "red", "FOO" = "green", "BAR" = "blue")

or use a ColorBrewer palette, as you do in the first example that works.

The second example does not work because you are asking for too many colors from the Set1 palette:

> library(RColorBrewer)
> brewer.pal(10, "Set1")
[1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00" "#FFFF33" "#A65628" "#F781BF" "#999999"
Warning message:
In brewer.pal(10, "Set1") :
  n too large, allowed maximum for palette Set1 is 9
Returning the palette you asked for with that many colors

When you ask ggnet or ggnet2 to use a ColorBrewer palette, it will automatically compute the right number of colors for your nodes, and will let you know if you need more node colors (in your case, that number is the number of unique values of the Kingdom variable) than there are colors in the palette.

My recommendation to you is to set the color palette manually, as suggested at the beginning of my answer. This seems to be the best solution in your case.

Simply make sure that you are writing your color palette vector correctly: the values of the vector should be colors, and the names of the vector should be the unique values of your Kingdom variable.

Hope this helps!

andrewd789 commented 8 years ago

Aha, thanks for the explanation, it's very helpful. Much appreciated.

A.