Roman_G
Roman_G

Reputation: 57

Custom colours for geom_ribbon fill based for categorical data

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)

Wrong color ribbons: enter image description here

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)

which results in red ribbons enter image description here

Any ideas? Thanks alot!

Upvotes: 1

Views: 6034

Answers (1)

John Harley
John Harley

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")) 

matching colors

Upvotes: 1

Related Questions