Geom_line和fill在ggplot中无法一起使用

时间:2020-05-06 10:46:59

标签: r ggplot2

似乎geom_line会干扰aes(fill=),因为:

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)

给我:

Error in FUN(X[[i]], ...) : object "Petal.Width" not found

有什么解释吗?

2 个答案:

答案 0 :(得分:2)

由于fill没有mtcars变量,因此您需要为第二个图使Petal.Width无效。

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)

答案 1 :(得分:2)

geom_line()从对ggplot()的主要调用中继承了总体情节美学。由于geom_line()数据没有Petal.Width列,因此该图层无法找到该图层的填充信息(也不用于一行)。为了省略这些内容,您可以设置inherit.aes = FALSE或将令人反感的美感移至正确的图层。

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)

移动填充美学的示例:

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)
相关问题