简体   繁体   中英

Geom_line and fill don't work together in ggplot

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?

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM