How can I use two different scale_fill_manual in ggplot command

This question follows from my earlier about background colors in ggplot2.

From the answers there, I can now use geom_rect to give a background to my plot, which has five different colors. In addition, I would like to build a barkar that uses two different colors. I can perform each of these tasks separately, but when I try to combine them, the scale_fill_manual commands scale_fill_manual .

Here is what I am trying:

 scores = data.frame(category = 1:4, percentage = c(34,62,41,44), type = c("a","a","a","b")) rects <- data.frame(ystart = c(0,25,45,65,85), yend = c(25,45,65,85,100), col = letters[1:5]) labels = c("ER", "OP", "PAE", "Overall") medals = c("navy","goldenrod4","darkgrey","gold","cadetblue1") ggplot() + geom_rect(data = rects, aes(xmin = -Inf, xmax = Inf, ymin = ystart, ymax = yend, fill=col), alpha = 0.3) + scale_fill_manual(values=medals) + opts(legend.position="none") + geom_bar(data=scores, aes(x=category, y=percentage, fill=type), stat="identity") + #scale_fill_manual(values = c("indianred1", "indianred4")) + scale_x_continuous(breaks = 1:4, labels = labels) 

As written, this makes the two barchart colors the same as the first two colors of the background. Removing the " # " in the second command scale_fill_manual (the penultimate line) cancels the background color commands to make the bars the colors I want, but makes the background have only the two colors I want in barchart .

How can I apply one scale_fill_manual command to the scale_fill_manual background and the other to barchart geom_bar (or how can I achieve the same effect in other ways)?

+8
r graph ggplot2
source share
1 answer

The problem is that you use "a" and "b" both rects and scores so that they appear in the same color. Since the rectangles seem to be placeholder values, change them to something different than anything in scores .

 rects$col <- c("Z1","Z2","Z3","Z4","Z5") 

Now you can do one scale_fill_manual with all colors (7).

 ggplot() + geom_rect(data = rects, aes(xmin = -Inf, xmax = Inf, ymin = ystart, ymax = yend, fill=col), alpha = 0.3) + opts(legend.position="none") + geom_bar(data=scores, aes(x=category, y=percentage, fill=type), stat="identity") + scale_fill_manual(values=c("indianred1", "indianred4", medals)) + scale_x_continuous(breaks = 1:4, labels = labels) 

enter image description here

+8
source share

All Articles