Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use different color palettes for different layers in ggplot2?

Is it possible to plot two sets of data on the same plot, but use different color palettes for each set?

testdf <- data.frame( x = rnorm(100), 
                  y1 = rnorm(100, mean = 0, sd = 1), 
                  y2 = rnorm(100, mean = 10, sd = 1),
                  yc = rnorm(100, mean = 0, sd = 3))
ggplot(testdf, aes(x, y1, colour = yc)) + geom_point() +
  geom_point(aes(y = y2))

What I would like to see is one set of data, say y1, in blues (color set by yc), and the other set in reds (again color set by yc).

The legend should then show 2 color scales, one in blue, the other red.

Thanks for your suggestions.

like image 838
drbv Avatar asked Feb 24 '12 08:02

drbv


People also ask

How do I specify colors in ggplot2?

A color can be specified either by name (e.g.: “red”) or by hexadecimal code (e.g. : “#FF1234”).

How do you combine color palettes?

You simply pick up a single colour and combine it with either various amounts of white or various amounts of black to create different tones and shades that stand out from each other. You can mix as much black or white to get the contrast that you want.

How do you get different colors in R?

In R, colors can be specified either by name (e.g col = “red”) or as a hexadecimal RGB triplet (such as col = “#FFCC00”). You can also use other color systems such as ones taken from the RColorBrewer package.

How do I use a custom palette in R?

To get your own palette up and running, you just need to swap in your own palette name where it says name = c(“insert your palette name here”), put that same palette name in place of 'your.palette.name'. Make sure you have named your red, green, and blue vectors r, g, b, respectively, and then you should be good to go.


2 Answers

If you translate the "blues" and "reds" to varying transparency, then it is not against ggplot's philosophy. So, using Thierry's Moltenversion of the data set:

ggplot(Molten, aes(x, value, colour = variable, alpha = yc)) + geom_point()

Should do the trick.

like image 138
cbeleites unhappy with SX Avatar answered Oct 19 '22 21:10

cbeleites unhappy with SX


That's not possible with ggplot2. I think it against the philosophy of ggplot2 because it complicates the interpreatation of the plot.

Another option is to use different shapes to separate the points.

testdf <- data.frame( x = rnorm(100), 
                      y1 = rnorm(100, mean = 0, sd = 1), 
                      y2 = rnorm(100, mean = 10, sd = 1),
                      yc = rnorm(100, mean = 0, sd = 3))
Molten <- melt(testdf, id.vars = c("x", "yc"))
ggplot(Molten, aes(x, value, colour = yc, shape = variable)) + geom_point()
like image 41
Thierry Avatar answered Oct 19 '22 23:10

Thierry