当我像这样在 aes 中使用颜色时
ggplot(data=olympia,aes(x=year)) + geom_line(aes(y=gold,colour="red")) + geom_line(aes(y=silver,colour="blue"))
Run Code Online (Sandbox Code Playgroud)
这是行不通的。
如果我使用 color 参数,它会显示正确的颜色红色和蓝色
ggplot(data=olympia,aes(x=year)) + geom_line(aes(y=gold),colour="red") + geom_line(aes(y=silver),colour="blue")
Run Code Online (Sandbox Code Playgroud)
有什么不同?有什么问题?
数据框
year gold silver
1 2002 12 16
2 2006 11 12
3 2010 10 13
4 2014 8 3
Run Code Online (Sandbox Code Playgroud)
不同之处在于,当您在 中提供 color 参数时aes,它会将其视为一个因子,并尝试将因子的每个级别映射到一个颜色(与您提供的方式相同c("USA", "USA", "Russia", "Russia")- 它不会将它们视为文字颜色)。
相反,当您直接将颜色赋予 时geom_line,它会将其作为实际颜色。您可以在以下文档中看到这一点geom_line:
Usage:
geom_line(mapping = NULL, data = NULL, stat = "identity",
position = "identity", ...)
<snip>
...: other arguments passed on to ‘layer’. This can include
aesthetics whose values you want to set, not map. See ‘layer’
for more details.
Run Code Online (Sandbox Code Playgroud)
请注意“您要设置其值,而不是映射”。