geom_ribbon填充的自定义颜色基于分类数据

时间:2017-10-10 17:38:34

标签: r ggplot2

我正在尝试使用scale_colour_manual中定义的自定义颜色来填充ggplot2中的geom_ribbon。以下是我从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)

错误的色带: enter image description here

显然,不使用为分类变量“类别”定义的颜色。而是使用默认调色板(scale_colour_hue?)。我可以将填充参数放在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)

导致红丝带 enter image description here

有什么想法吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

尝试使用scale_color_manual参数中定义的相同颜色添加scale_fill_manual。

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