首先我运行这段代码,它运行良好(所有数据点都变成蓝色):
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()
首先我运行这段代码,它运行良好(所有数据点都变成蓝色):
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()
您可以在几何之间的映射中共享变量。具体来说color
,它需要aes
在geom
设置为常量(例如"blue"
)而不是变量(此处解释:回答:参数何时进入 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)