首先,我运行此代码并且它完美运行(所有数据点都变为蓝色):
ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy), color = "blue")
但是当我尝试移动下面的映射时,数据点变为黑色而不是蓝色。
为什么?
ggplot(data = mpg, mapping = aes(x = displ, y = hwy), color = "blue") + geom_point()
答案 0 :(得分:0)
您可以在几何之间的映射内共享变量。特别是关于color
,当设置为常量(例如aes
)而不是变量(在此处说明时),需要在geom
外部和"blue"
中进行定义。 Answer to: When does the argument go inside or outside aes。
我在下面提供了一些示例,以更好地说明这一点;
library(ggplot2)
## works fine for each geom
ggplot(data = mpg, aes(x = displ, y = hwy)) +
geom_point(color = "blue") +
geom_line(color="red")
## doesn't work when not in the geom
ggplot(data = mpg, aes(x = displ, y = hwy), color = "blue") +
geom_point()
## gets evaluated as a variable when in aes
ggplot(data = mpg, aes(x = displ, y = hwy)) +
geom_point(aes(color = "blue"))
## can use a variable in aes, either in geom or ggplot function
ggplot(data = mpg, aes(x = displ, y = hwy)) +
geom_point(aes(color = model), show.legend = FALSE)