This question follows on from my earlier one about background colours in ggplot2.
From the answers there, I am now able to use geom_rect
to give a background to my plot that has five different colours. On top of that I'd like to plot a barchart that uses two different colours. I can do each of these tasks separately, but when I try to combine them the scale_fill_manual
commands clash.
Here's what I'm 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 colours the same as the first two background colours. Removing the "#
" on the second scale_fill_manual
command (penultimate line) overrides the background colour commands to make the bars the colours I want but makes the background have just the two colours I want in the barchart
.
How can I have one scale_fill_manual
command applying to the geom_rect
background and the other to the geom_bar
barchart (or how can I achieve the same effect by other means)?
The problem is that you are using
"a"
and"b"
in bothrects
andscores
, so they get mapped to the same color. Since the rectangles seem to be placeholder values, change them to something distinct that sorts later than anything inscores
.Now you can make one
scale_fill_manual
with all (7) colors.