Reputation: 157
it seems that geom_line
interferes with aes(fill=)
since:
ggplot(iris, aes(Sepal.Width, Sepal.Length,
fill = Petal.Width))+
geom_point(shape = 21)+
scale_fill_gradient(low="orange",high="blue")+
geom_line(aes(cyl, am), mtcars)
Gives me:
Error in FUN(X[[i]], ...) : object "Petal.Width" not found
Any explanations?
Upvotes: 2
Views: 687
Reputation: 6750
You need to nullify fill
for your second plot since mtcars
does not have Petal.Width
variable.
library(ggplot2)
ggplot(iris, aes(Sepal.Width, Sepal.Length,
fill = Petal.Width))+
geom_point(shape = 21)+
scale_fill_gradient(low="orange",high="blue")+
geom_line(aes(cyl, am, fill=NULL), mtcars)
Upvotes: 3
Reputation: 38063
The geom_line()
inherits global plot aesthetics from the main call to ggplot()
. Since the geom_line()
data doesn't have a Petal.Width
column, the layer cannot find the fill information for that layer (nor is it used for a line). In order to omit these, you can set inherit.aes = FALSE
or move the offending aesthetic to the correct layers.
Example of inherit.aes
ggplot(iris, aes(Sepal.Width, Sepal.Length,
fill = Petal.Width))+
geom_point(shape = 21)+
scale_fill_gradient(low="orange",high="blue")+
geom_line(aes(cyl, am), mtcars, inherit.aes = FALSE)
Example of moving the fill aesthetic:
ggplot(iris, aes(Sepal.Width, Sepal.Length))+
geom_point(aes(fill = Petal.Width), shape = 21)+
scale_fill_gradient(low="orange",high="blue")+
geom_line(aes(cyl, am), mtcars)
Upvotes: 2