使用 ggplot()更改行颜色

我并不经常使用 ggplot2,但是今天我想在一些图表上尝试一下。但是我不知道如何在 geom_line()中手动控制颜色

我确信我忽略了一些简单的东西,但这里是我的测试代码:

x <- c(1:20, 1:20)
variable <- c(rep("y1", 20), rep("y2", 20) )
value <- c(rnorm(20), rnorm(20,.5) )


df <- data.frame(x, variable, value )


d <- ggplot(df, aes(x=x, y=value, group=variable, colour=variable ) ) +
geom_line(size=2)
d

这给了我预期的结果:

enter image description here

我以为我要做的就是这么简单:

d +  scale_fill_manual(values=c("#CC6666", "#9999CC"))

但这改变不了什么,我错过了什么?

231863 次浏览

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

Here's a minimal reproducible example of another way to change line colours (try running it):

library(tidyverse)
library(ggplot2)


iris %>%
ggplot(aes(x = Petal.Length)) +
geom_line(aes(y = Sepal.Length), color = "green") +
geom_line(aes(y = Sepal.Width), color = "blue")

enter image description here

This way can be particularly useful when you added the lines manually.