简体   繁体   English

Geom_line 和 fill 在 ggplot 中不能一起工作

[英]Geom_line and fill don't work together in ggplot

it seems that geom_line interferes with aes(fill=) since:似乎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)

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.您需要为第二个 plot 取消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)

The geom_line() inherits global plot aesthetics from the main call to ggplot() . geom_line()从对ggplot()的主要调用继承了全局 plot 美学。 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).由于geom_line()数据没有Petal.Width列,因此该图层无法找到该图层的填充信息(也不用于线条)。 In order to omit these, you can set inherit.aes = FALSE or move the offending aesthetic to the correct layers.为了省略这些,您可以设置inherit.aes = FALSE或将有问题的美学移动到正确的层。

Example of inherit.aes 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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