Reputation: 57
I'm trying to use custom colours defined in scale_colour_manual to fill a geom_ribbon in ggplot2. Here is an example I took from Custom ggplot2 shaded error areas on categorical line plot:
set.seed(12345)
data <- cbind(rep("A", 100), rnorm(100, 0, 1))
data <- rbind(data, cbind(rep("B", 100), rnorm(100, 5, 1)))
data <- rbind(data, cbind(rep("C", 100), rnorm(100, 10, 1)))
data <- rbind(data, cbind(rep("D", 100), rnorm(100, 15, 1)))
data <- cbind(rep(1:100, 4), data)
data <- data.frame(data)
names(data) <- c("num", "category", "value")
data$num <- as.numeric(data$num)
data$value <- as.numeric(data$value)
data$upper <- data$value+10
data$lower <- data$value-10
data = data[order(data$category, data$num),]
data$upperLoess = unlist(lapply(LETTERS[1:4],
function(x) predict(loess(data$upper[data$category==x] ~
data$num[data$category==x]))))
data$lowerLoess = unlist(lapply(LETTERS[1:4],
function(x) predict(loess(data$lower[data$category==x] ~
data$num[data$category==x]))))
ggplot(data, aes(num, value, colour=category, fill=category)) +
scale_colour_manual(values = c("A"="black", "B"="red", "C"="magenta", "D"="green")) +
geom_smooth(method="loess", se=FALSE) +
geom_ribbon(aes(x=num, ymax=upperLoess, ymin=lowerLoess, fill=category),
alpha=0.2)
Obviously, the colours defined for the categorical variable "category" are not used. Instead, the default palette (scale_colour_hue?) is used. I can place the fill argument outside the aes:
ggplot(data, aes(num, value, colour=category, fill=category)) +
scale_colour_manual(values = c("A"="black", "B"="red", "C"="magenta", "D"="green")) +
geom_smooth(method="loess", se=FALSE) +
geom_ribbon(aes(x=num, ymax=upperLoess, ymin=lowerLoess), fill="red",
alpha=0.2)
Any ideas? Thanks alot!
Upvotes: 1
Views: 6034
Reputation: 176
Try adding scale_fill_manual using the same colors defined in you scale_color_manual argument.
ggplot(data, aes(num, value, colour=category, fill=category)) +
scale_colour_manual(values = c("A"="black", "B"="red", "C"="magenta", "D"="green")) +
geom_smooth(method="loess", se=FALSE) +
geom_ribbon(aes(x=num, ymax=upperLoess, ymin=lowerLoess, fill=category),
alpha=0.2) +
scale_fill_manual(values = c("A"="black", "B"="red", "C"="magenta", "D"="green"))
Upvotes: 1