首页 > 解决方案 > 在ggplot中使用aes的两种方式有什么区别?

问题描述

我最近开始学习 R,但对 ggplot2 中的 aes 功能感到困惑。

我已经看到两个不同的地方 aes 被放置在代码中。

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy))

ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point()

两者有什么区别?

标签: rggplot2

解决方案


找不到骗子,所以这里有一个答案:

中指定的美学ggplot()由后续层继承。在特定层中指定的美学仅特定于该层。这是一个例子:

library(ggplot2)

ggplot(mtcars, aes(wt, mpg)) +
  geom_point() + 
  geom_smooth()

ggplot(mtcars) +
  geom_point(aes(wt, mpg)) + 
  geom_smooth()  # error, geom_smooth needs its own aesthetics

当您希望不同的层具有不同的规格时,这非常有用,例如这两个图是不同的,您必须决定您想要哪个:

ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
  geom_point() + 
  geom_smooth()

ggplot(mtcars, aes(wt, mpg)) +
  geom_point(aes(color = factor(cyl))) + 
  geom_smooth()

在单个图层上,您可以使用inherit.aes = FALSE来关闭该图层的继承。如果您的大多数图层都使用相同的美学,但少数不这样做,这将非常有用。


推荐阅读